Jsonp, jsonp cross-Origin

Source: Internet
Author: User

Jsonp, jsonp cross-Origin

Jsonp


We know that normal ajax requests have no cross-origin access permission. This is the function of the browser's security policy.

Index. php:

<?php $info = '{"code" : 10,"title" : "jsonp","name" : "rgy"}';echo $info;?>

Js Code in test.html:

$.ajax({      type: "post",      url: "http://localhost/jsonptest/index.php",      dataType: "json",      success: function(data) {          console.log(data);      },      error: function(data) {          console.log("fail");      }});

For example, test.htmland index.php#are in the same domain. When test.html accesses index. php:, it usually appears as shown in:


How can this problem be solved?

There are two ideas:

The first is to modify the server code by adding the header (Access-Control-Allow_Origin: *) to index. php; allowing requests from all sources to access the resource.

The second approach is to use jsonp.


The first method is introduced below:

Modify index. php to the following format:

<?php header('Access-Control-Allow-Origin:*'); ?><?php $info = '{"code" : 10,"title" : "jsonp","name" : "rgy"}';echo $info;?>
If test.html is used for cross-origin access, the result is as follows:



Method 2:

First, change the server code to the following format:

<?php    $callback = $_GET['callback'];  $info = '{"code":10,"title":"jsonp","name":"rgy"}';echo $callback."(".$info.")";?>
You can access test.html as follows:

$.ajax({        type: "get",        url: "http://todolist6.sinaapp.com/pages/QuickWayGetInfo.php",        dataType: "jsonp",        jsonp: "callback",        success: function(data) {            console.log(data);        },        error: function() {            console.log("fail");        }<span style="white-space:pre"></span>});
$.getJSON("http://todolist6.sinaapp.com/pages/QuickWayGetInfo.php?callback=?",function(data){       console.log(data);    }); 
The result is as follows:



This is a good method encapsulated by jquery. Although it is easy to use, it is not conducive to understanding the principles of jsonp. below is the native js to simulate the jsonp access process.

To put it bluntly, it is the cross-origin access feature using the src attribute.

var showInfo = function(data){ console.log(data);}var url = "http://todolist6.sinaapp.com/pages/QuickWayGetInfo.php?callback=showInfo";var script = document.createElement('script');script.setAttribute('src', url);document.getElementsByTagName('head')[0].appendChild(script);
Define a callback method showInfo and send it to the server as a part of the url parameter. The server wraps the data in the callback method by concatenating strings and returns the result.

However, this process is quite inconvenient to use and is encapsulated without using other js libraries:

Function loadScript (xyUrl, callback) {var head = document. getElementsByTagName ('head') [0]; var script = document. createElement ('script'); script. type = 'text/javascript '; script. src = xyUrl; script. onload = script. onreadystatechange = function () {if ((! This. readyState | this. readyState = "loaded" | this. readyState = "complete") {callback & callback (); // Handle memory leak in IE script. onload = script. onreadystatechange = null; // manually reclaim the memory if (head & script. parentNode) {head. removeChild (script) ;}}; head. insertBefore (script, head. firstChild);} // var url = "http://todolist6.sinaapp.com/pages/QuickWayGetInfo.php? Callback = showInfo "; loadScript (url, showInfo); var showInfo = function (data) {console. log (data. name );}

Summary:

Jsonp uses the src attribute in the <script> tag to enable cross-origin access. It first defines a callback method and sends it to the server as part of the url parameter, the server wraps the data in the callback method by concatenating strings, and then returns


Ajax and jsonp are actually different in nature. Although jquery integrates them together, the core of ajax is to obtain non-page content through XmlHttpRequest, the core of jsonp is to dynamically Add the <script> tag to call the js script provided by the server.


Jsonp is a non-mandatory protocol, or it is more like a method. Like ajax, jsonp does not have to transmit data in json format, as long as the returned content is an executable js script.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.