Ajax cross-Domain--jsop method

Source: Internet
Author: User

1. What is JSONP?

To understand JSONP, you have to mention JSON, so what is JSON?

JSON is simply the objects and arrays in JavaScript, so these two structures are objects and arrays of two structures, through these two structures can represent a variety of complex structure 1, objects: objects in JS represented as "{}" in the content, the data structure is {key:value, Key:value,...} The structure of key-value pairs, in object-oriented languages, key is the property of the object, value is the corresponding property value, so it is easy to understand that the value method is the object. Key Gets the property value, the type of the property value can be a number, a string, an array, several objects. 2, array: The array in JS is the middle bracket "[]" in the content, data structure for ["Java", "JavaScript", "VB",...], the value way and all languages, using index get, the type of field value can be number, string, array, object several.
 is Object  is  in the language with no muss or fuss.

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

2. What is the use of JSONP?

Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then output JSON data on the server and execute callback functions to resolve cross-domain data requests.

3, how to use JSONP?

The demo below is actually a simple representation of JSONP, after the client declares the callback function, the client requests data across the domain through the script tag, then the server returns the corresponding data and executes the callback function dynamically.

HTML code (either):

HTML code
<meta content="text/html; Charset=utf-8"http-equiv="Content-type"/> <script type="Text/javascript">function Jsonpcallback (result) {//alert (result);          for(varIinchresult) {Alert (i+":"+result[i]);//loop output a:1,b:2,etc.         }      }      varJsonp=document.createelement ("Script"); Jsonp.type="Text/javascript"; JSONP.SRC="Http://crossdomain.com/services.php?callback=jsonpCallback"; document.getElementsByTagName ("Head")[0].appendchild (JSONP); </script>

Or

HTML code
  1. <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(varIinchresult) {Alert (i+":"+result[i]);//loop output a:1,b:2,etc.         }      }  </script> <script type="Text/javascript"Src="Http://crossdomain.com/services.php?callback=jsonpCallback"></script>

JavaScript links must be under function.

Server PHP Code (services.php):

PHP code
  1. //The service side returns JSON data$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) "; //Dynamic Execution callback function$callback =$_get['Callback']; Echo $callback."($result)"; 

If the above JS client code is implemented in jquery, it is also very simple.

$.getjson
$.ajax
$.get

How to implement the client JS code in jquery 1:

JS Code
<script type="Text/javascript"Src="Jquery.js"></script> <script type="Text/javascript">$.getjson ("http://crossdomain.com/services.php?callback=?", function (result) { for(varIinchresult) {Alert (i+":"+result[i]);//loop output a:1,b:2,etc.         }      }); </script>

How to implement the client JS code in jquery 2:

JS Code
<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(varIinchresult) {Alert (i+":"+result[i]);//loop output a:1,b:2,etc. }}, timeout: the      }); </script>

How to implement the client JS code in jquery 3:

JS Code
<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(varIinchJSON) alert (i+":"+json[i]); },'Jsonp'); </script>

Where Jsoncallback is a function that is registered by the client and gets the JSON data on the cross-domain server after the callback.
Http://crossdomain.com/services.php?callback=jsonpCallback
This URL is a cross-domain server to take JSON data interface, the parameter is the name of the callback function, the return format is

JS Code
    1. Jsonpcallback ({msg:'This isJSON data'})  

Jsonp principle:
First register a callback with the client and then pass the callback name to the server.

At this point, the server becomes JSON data.
Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

The advantage of using JSON is that:

    • It's a lot lighter than XML, and it's not that much redundant stuff.
    • JSON is also very readable, but usually the return is compressed. Unlike a browser like XML can be directly displayed, the browser for the format of JSON display will need to use some plug-ins.
    • Working with JSON in JavaScript is simple.
    • Other languages such as PHP support for JSON is also good.

JSON also has some disadvantages:

    • JSON support in the service-side language is not as extensive as XML, but it json.org a library of many languages.
    • If you use eval () to parse, you are prone to security issues.

However, the advantages of JSON are obvious. He is an ideal data format for AJAX data interactions.

Main tips:

JSONP is a powerful technology for building mashups, but unfortunately it is not a panacea for all cross-domain communication needs. It has some drawbacks that must be carefully considered before submitting development resources.

First, and most important, there is no error handling on the JSONP call. If the dynamic script insert is valid, the call is executed, and if it is not valid, the silence fails. There is no hint of failure. For example, you cannot catch a 404 error from the server, and you cannot cancel or restart the request. However, waiting for a period of time has not responded, do not have to ignore it. (The future JQuery version may have the feature to terminate the JSONP request.)

Another major drawback of JSONP is the danger of being used by untrusted services. Because the JSONP service returns a JSON response packaged in a function call, the function call is executed by the browser, which makes the host WEB application more susceptible to various types of attacks. If you intend to use the JSONP service, it is important to understand the threats it can pose.

Ajax cross-Domain--jsop method

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.