You don't know. jquery Item11--Ajax Jsonp cross-domain approach

Source: Internet
Author: User
Tags package json

Starting with the difference between JSON and JSONP, the article uses examples to compare the differences between them, then explains in detail the use of Ajax Jsonp in jquery and gives examples and detailed parameter descriptions.

1.JSON and Jsonp

  JSON(JavaScript Object Notation) is a lightweight data interchange format for exchanging information between a browser and a server.

  JSONP (JSON with Padding), is packaged in the function call in the JSON (or package JSON), you want to cross-domain request other People's things, you must wrap up, do not pollute the other people's things, the JSON data wrapped up called JSONP, personal Understanding, haha ~ ~.

  JSON is a data format, and JSONP is a way to call data.

//JSON { “name”: “肖果平” }
//JSONPcallback({ “name”: “小平果” })

  
For security reasons, scripting (AJAX) cannot access content that is not part of the domain. However, static resources are not restricted by the domain policy, can load arbitrary domain scripts, styles, pictures and other static resources, JSOP is to use this principle to achieve cross-domain data acquisition.

Example 1:

 //定义shoPrice函数,处理返回来的data数据 function showPrice(data) {     alert("Symbol: " + data.symbol + ", Price: " + data.price); }

The code is as follows:

Include Showprice functions and parameters in a Web page<script type="Text/javascript">  function showprice(data) { alert ("Symbol:" + Data.symbol + ", P Rice: " + Data.price);}</script> <script type="Text/javascript">Showprice ({symbol: ' IBM ', Price: 91.42});</script>

  
This example shows how to call a JavaScript function with static JSON data as a parameter.

Example 2:

The first function call can be completely written in a JS file on the server, loaded into the page with a script tag, and this tag can be created dynamically.

The code is as follows:

 <script type="Text/javascript"> function  showprice   { //This is Our function to is called with JSON data  alert ( "Symbol:"  + Data.symbo L +  + Data.price);} var  url = "Remote.js"; //the URL of the external script  //dynamic Insert Script  var  script = document.createelement ( ' script ' ); Script.setattribute ( ' src ' , url); //load script  document.getelementsbytagname ( ' head ' ) [0 ].appendchild (script); </script>

The contents of Remote.js are the same as those previously written in the label:

showPrice({symbol: ‘IBM‘, price: 91.42

Dynamically inserted JavaScript code, the JSON data to be passed as a parameter, showprice the arguments of the function call statement.

So the question comes, do you call the Showprice function every time you get the data? This requires the front-end program ape to make a pact, of course, this has a lot of inconvenience, especially for open interfaces to the public to develop the situation. Jsop this: supports the front end passing a callback function name parameter, the backend receives the callback function name parameter, then generates a call to the function, passes the JSON data as a parameter, and inserts it into the page when the client arrives to execute.

Example 3:

Dynamic insert code with callback parameters:

The code is as follows:

 <script  type  =< Span class= "Hljs-value" > "Text/javascript" ;  //this is we function to being called with JSON data  function  showprice   { alert ( "Symbol:"  + Data.symbol +  + Data.price); } var  url = "Remote.js?callback= ' Showprice ' "; //the URL of the external script  //dynamic Insert Script  var  script = document.createelement ( ' script ' ); Script.setattribute ( ' src ' , url); //load script  document.getelementsbytagname ( ' head ' ) [0 ].appendchild (script); </script>

Code snippet for the JSONP service implemented by the backend in PHP:

The code is as follows:

$jsonData = getDataAsJson($_GET[‘symbol‘echo$_GET[‘callback‘‘(‘$jsonData‘);‘; //这里接收到$_GET[‘callback‘] =showPrice; // 打印: showPrice({"symbol""IBM""price""91.42"});

This is a good fit for the definition of JSONP, which is packaged in JSON data in function calls.

If you look dizzy, say a little easier!!!

The browser is not allowed to request data directly across domains, JSONP is to use the script tag to get data across domains to work

Steps:

1. Build a function, this function name (in this case the jsonpcallback is to be passed to the backend)

<meta content="text/html; Charset=utf-8 " http-equiv=" Content-type " /><script type="Text/javascript"> function  jsonpcallback   { //    alert (result);  for  (var  i in  result) {Alert (I+ +result[i]);    //loop output 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>

2. Create a new script tag, src points to the domain name

3. Insert the script into the body

The front-end part is.

————————————–

Implemented with jquery

  $.ajax({      ‘http://10.95.192.27:8080/honeybee/zhuanti/export.action‘,      "jsonp",      "topicsCallback",      function(){}  });

JSONP: The name that is fixed with the backend. The specific processing function is in the success.

2. Using Jsonp in jquery

  Ajax and Jsonp in jquery seem to be very similar, do not be confused by this phenomenon, they are very different in nature. Ajax is to get non-page content through XMLHttpRequest objects, while Jsonp is dynamically added

 $.ajax ({URL:  "/http" Query.yahooapis.com/v1/public/yql ", Jsonpcallback: " Showprice ", Jsonp: 
    
      "callback" , 
     //tell JQuery we ' re expecting JSONP  D Atatype: 
      "Jsonp" , data: {Q: 
      "select Title,abstract , URL from search.news where query=\ "cat\" ", Format: 
     " JSON "}, 
     
      //work with the response  success: 
      function   { console.log (data); //server response } });
     
    

Ajax Request Parameter Description:
DataType String
Expected data type returned by the server. If not specified, JQuery is automatically judged intelligently based on the HTTP packet mime information, such as the XML MIME type being recognized as XML. In 1.4, JSON generates a JavaScript object, and script executes it. The data returned by the server is then parsed against this value and passed to the callback function. Available values:

    • "xml": Returns an XML document that can be processed with jQuery.
    • HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
    • "Script": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. "' Note: ' On a remote request (not under the same domain), all post requests are converted to get requests. (because the script tag of the DOM will be used to load)
    • "JSON": Returns the JSON data.
    • "Jsonp": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.
    • "Text": Returns a plain text string

Jsonp

Overrides the name of the callback function in the JSONP request. Used to replace the “callback=?” "callback" part of this Get or POST request URL parameter, such as {jsonp:‘onJsonPLoad‘} causing "onjsonpload" to be passed to the server.

Jsonpcallback,

Specifies a callback function name for JSONP. This value will be used instead of the random function name generated by jquery automatically. This is primarily used to create a unique function name for jquery, which makes it easier to manage requests and provides a convenient way to provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache a GET request. However, the actual use of the process, do not write callback functions, such as the showprice in this example, do not write or error, because jquery in the process of JSONP, automatically help you generate a callback function and take the data out to success method calls. It might look like this:
The code is as follows:

function success_jsonpCallback(data) { success(data); }  

The above is the whole content of this article, whether we have a detailed understanding of the JSONP. If you have any questions, please leave me a message and discuss it together.

Find a good example on the Internet, share out, very clear contrast, self-test.

<html><head>    <title>JQuery $.ajax Jsonp</title>    <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 " />    <meta http-equiv="Content-language" Content="ZH-CN" / >    <script type="text/javascript" src="http// Files.cnblogs.com/zjmainstay/jquery-1.6.2.min.js "></script></head><body><div id="MyData"></div><script type="Text/javascript">/* The current file is: http://www.test.com/index.html*/$ (document). Ready ( function(){$.ajax ({URL:' http://www.wp.com/getData.php ',//cross-domain to http://www.wp.com, and http://test.com is also cross-domainType' GET ',//JSONP type can only use GET, cannot use post, here does not write default to getDataType:' Jsonp ',//specified as JSONP typedata:{"Name":"Zjmainstay"},//Data ParametersJsonp' Callback ',//server side get callback function name of key, corresponding background has $_get[' callback ']= ' GetName '; callback is the default valueJsonpcallback:' GetName ',//callback function nameSuccess function(Result){                  //successfully performed processing, corresponding to the GetName (data) method returned by the backend. $("#myData"). HTML (' 1, My name is '+result.name+'. I\ ' m '+result.age+' Years old.<br/> '); }, Error: function(msg){Alert (Msg.tosource ());//Execution Error}    });/ * This is not a cross-domain * /$.ajax ({URL:' http://www.test.com/getData.php ',//Normal        //url: ' http://test.com/getData.php ',//cross-domain to http://test.comType' GET ',//This is normal Ajax, you can use postDataType:' JSON ', data:{"Name":"Zjmainstay"}, Success: function(Result){$("#myData"). Append (' 2, My name is '+result.name+'. I\ ' m '+result.age+' years old. '); }, Error: function(msg){Alert (Msg.tosource ());//cross-domain error will be executed here}    });});</script></body></html>

Files: http://www.wp.com/getData.php

<?php    $data = array(        "name"=>$_GET[‘name‘],        "age"=>23,    );    echo $_GET[‘callback‘]."(".json_encode($data).")";        //等价:echo ‘getName({"name":"Zjmainstay","age":23})‘;?>

Files: http://www.test.com/getData.php (not cross-domain), same as http://test.com/getData.php (cross-domain)

<?php    $data = array(        "name"=>$_GET[‘name‘],        "age"=>23,    );    echo json_encode($data);?>

You don't know. jquery Item11--Ajax Jsonp cross-domain approach

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.