Solution to ajax cross-domain request: use JSONP to obtain JSON data
Due to browser restrictions, ajax does not allow cross-domain communication. If you try to request data from a different domain, a security error will occur. These security mistakes can be avoided if you can control the remote server where the data resides and if every request goes to the same domain. But what good is a web application if it just stays on its own server? What if you need to collect data from multiple third-party servers?
Understand Same Origin Policy Restrictions
The Same Origin Policy prevents scripts loaded on one domain from obtaining or manipulating document properties on another domain. That is, the domain of the requested URL must be the same as the domain of the current web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is old and has existed since Netscape Navigator version 2.0.
A relatively simple way to overcome this limitation is to have the web page request data from the web server it originated from, and have the web server act like a proxy and forward the request to the real third-party server. Although this technology has gained widespread use, it is not scalable. Another way is to use frame elements to create a new area within the current web page and use GET requests to obtain any third-party resources. However, after obtaining the resources, the content in the frame will be restricted by the same-origin policy.
A more ideal way to overcome this limitation is to insert a dynamic script element into the web page whose source points to a service URL in another domain and obtain the data in its own script. It starts execution when the script is loaded. This approach works because the Same Origin Policy does not prevent dynamic script insertion and the script is treated as if it were loaded from the domain that serves the Web page. But if the script tries to load the document from another domain, it won't succeed. Fortunately, this technique can be improved upon by adding JavaScript Object Notation (JSON).
What is JSONP?
To understand JSONP, we have to mention JSON, so what is JSON?
JSONP (JSON with Padding) is an unofficial protocol that allows integrating Script tags on the server side and returning them to the client, achieving cross-domain access through javascript callback (this is just a simple implementation of JSONP).
What is JSONP used for?
Due to the restriction of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). In order to implement cross-domain requests, you can implement cross-domain requests through script tags, and then output JSON data on the server side and execute callbacks. function to solve cross-domain data requests.
How to use JSONP?
The DEMO below is actually a simple representation of JSONP. After the client declares the callback function, the client requests cross-domain data from the server through the script tag, and then the server returns the corresponding data and dynamically executes the callback function.
1. HTML code (either):
<meta content=“text/html; charset=utf-8″ http-equiv=“Content-Type” /> <script type=“text/javascript”> function jsonpCallback(result) { //alert(result); for(var i in result) { alert(i+”:”+result[i]);//循环输出a:1,b:2,etc. } } var JSONP=document.createElement(“script”); JSONP.type=“text/javascript”; JSONP.src=“http://crossdomain.com/services.php?callback=jsonpCallback”; document.getElementsByTagName(“head”)[0].appendChild(JSONP); </script>
or
<meta content=“text/html; charset=utf-8″ http-equiv=“Content-Type” /> <script type=“text/javascript”> function jsonpCallback(result) { alert(result.a); alert(result.b); alert(result.c); for(var i in result) { alert(i+”:”+result[i]);//循环输出a:1,b:2,etc. } } </script> <script type=“text/javascript” src=“http://crossdomain.com/services.php?callback=jsonpCallback”> </script>
JavaScript link must be below the function.
2. Server-side PHP code
<?php //服务端返回JSON数据 $arr=array(‘a’=>1,‘b’=>2,‘c’=>3,‘d’=>4,‘e’=>5); $result=json_encode($arr); //echo $_GET['callback'].’(“Hello,World!”)’; //echo $_GET['callback'].”($result)”; //动态执行回调函数 $callback=$_GET[‘callback’]; echo $callback.“($result)”;
3. jQuery implementation
Implementation method of client JS code in jQuery 1:
<script type=“text/javascript” src=“jquery.js”></script> <script type=“text/javascript”> $.getJSON(“http://crossdomain.com/services.php?callback=?”, function(result) { for(var i in result) { alert(i+“:”+result[i]);//循环输出a:1,b:2,etc. } }); </script>
Implementation method of client JS code in jQuery 2:
<script type=“text/javascript” src=“jquery.js”></script> <script type=“text/javascript”> $.ajax({ url:“http://crossdomain.com/services.php”, dataType:‘jsonp’, data:”, jsonp:‘callback’, success:function(result) { for(var i in result) { alert(i+“:”+result[i]);//循环输出a:1,b:2,etc. } }, timeout:3000 }); </script>
Client JS Implementation method 3 of the code in jQuery:
<script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $.get('http://crossdomain.com/services.php?callback=?', {name: encodeURIComponent('tester')}, function (json) { for(var i in json) alert(i+':'+json[i]); }, 'jsonp'); </script>
Among them, jsonCallback is registered by the client and is a callback function after obtaining the json data on the cross-domain server.
http://crossdomain.com/services.php?callback=jsonpCallback
This url is the interface for fetching json data from cross-domain servers. The parameter is the name of the callback function. The returned format is
jsonpCallback({msg:'this is json data'})
jsonp principle:
First register a callback on the client, and then pass the callback name to the server .
At this time, the server generates json data first.
Then use javascript syntax to generate a function. The function name is the passed parameter jsonp.
Finally, the json data is directly placed into the function as a parameter, thus generating a js syntax document. Returned to the client.
The client browser parses the script tag and executes the returned javascript document. At this time, the data is passed as a parameter to the callback function predefined by the client. (Dynamic execution of the callback function)
The advantage of using JSON is:
It is much lighter than XML and does not have so many redundant things.
JSON is also very readable, but it is usually returned compressed. Unlike XML, which can be displayed directly by browsers, browsers need to use some plug-ins to format JSON.
Handling JSON in JavaScript is easy.
Other languages such as PHP also have good support for JSON.
JSON also has some disadvantages:
JSON’s server-side language support is not as extensive as XML, but JSON.org provides libraries for many languages.
If you use eval() to parse, security issues may easily arise.
Nonetheless, the advantages of JSON are still obvious. It is an ideal data format for Ajax data interaction.
Key Tip:
JSONP is a powerful technology for building mashups, but unfortunately, it is not a panacea for all cross-domain communication needs. It has some flaws, which must be carefully considered before committing resources to development.
First, and most importantly, there is no error handling for JSONP calls. If the dynamic script insertion is valid, the call is executed; if it is invalid, it fails silently. There is no prompt for failure. For example, 404 errors cannot be caught from the server, and requests cannot be canceled or restarted. However, if there is no response after waiting for a while, ignore it. (Future versions of jQuery may have features to terminate JSONP requests).
Another major drawback of JSONP is that it can be dangerous when used by untrusted services. Because the JSONP service returns a JSON response wrapped in a function call that is executed by the browser, it makes the host web application more vulnerable to a variety of attacks. If you plan to use a JSONP service, it's important to understand the threats it can pose.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON
