Home > Web Front-end > JS Tutorial > body text

Solution to ajax cross-domain request: use JSONP to obtain JSON data

伊谢尔伦
Release: 2016-11-23 14:39:02
Original
1198 people have browsed it

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>
Copy after login

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>
Copy after login

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[&#39;callback&#39;].’(“Hello,World!”)’;  
//echo $_GET[&#39;callback&#39;].”($result)”;  
//动态执行回调函数  
$callback=$_GET[‘callback’];  
echo $callback.“($result)”;
Copy after login

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>
Copy after login

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>
Copy after login

Client JS Implementation method 3 of the code in jQuery:

<script type=&#39;text/javascript&#39; src=&#39;jquery.js&#39;></script>  
<script type=&#39;text/javascript&#39;>  
    $.get(&#39;http://crossdomain.com/services.php?callback=?&#39;, 
        {name: encodeURIComponent(&#39;tester&#39;)},         
        function (json) { for(var i in json) alert(i+&#39;:&#39;+json[i]); }, &#39;jsonp&#39;);  
</script>
Copy after login

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
Copy after login

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:&#39;this is json data&#39;})
Copy after login

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.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template