Use of JSONP and callback

Source: Internet
Author: User
Tags script tag

These two days with Jquery cross-domain fetch data, often encountered invalid label this error, very depressed, always get the server side sent back JSON value,

The two methods commonly used across domains are: $.ajax and $.getjson

Finally, carefully quiet down, read the official JSON document after the discovery of such a paragraph:

JSON data is a structured data that can be easily parsed by JavaScript. If the obtained data file resides on the remote server (the domain name is different, that is, the data is obtained across domains), you need to use the JSONP type. With this type, a query string parameter callback= is created? , this parameter is appended to the URL of the request. The server side should precede the JSON data with a callback function name in order to complete a valid JSONP request. If you want to specify the parameter name of the callback function instead of the default callback, you can set the JSONP parameter of the $.ajax ().

In fact, the principle of jquery cross-domain is implemented through the outer chain <script>, and then in the callback function plus the callback function parameters to achieve true cross-domain

Jquery in each cross-domain send the request will have callback this parameter, in fact, the value of this parameter is the callback function name, so the server side in the sending of JSON data, should be put in front of this parameter, the value of this parameter is often randomly generated, such as: jsonp1294734708682, you can also set the name of the callback method by using the $.ajax method. Once the principle is understood, the server should send data like this:

String message = "jsonp1294734708682 ({\" userid\ ": 0,\" username\ ": \" Null\ "})";

In this way, the JSON data {\ "userid\": 0,\ "username\": \ "Null\"} is used as a parameter of the jsonp1294734708682 callback function

Let's start with an example.

If the data returned normally:

{"Success": [{"id": 1, "title": "Title 1"}, {"id": 2, "title": "Title 2"}, {"id": 3, "title": "Title 3"}]}

Let's introduce our own parameters for jquery.

/* * * @dataType (String) * "XML": Returns an XML document that can be processed using JQuery. * "HTML": Returns plain text HTML information; The included script tag is executed when the DOM is inserted. * "Script": Returns plain text JavaScript code. "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 (String) overrides the name of the callback function in a JSONP request. * This value is used instead of "callback=?" The "callback" part of the URL parameter in this get or POST request, * such as {jsonp: ' onjsonpload '} will cause the "onjsonpload=?" passed to the server.  */* * * @jsonpCallback (String) * Specify a callback function name for the JSONP request. 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. */

1 do not specify the name of the JSONP

$.ajax ({    ' http://lifeloopdev.info/get_events ',    "Jsonp",    "offset=0& Num_items=10 ",    ' username ',    ' password ',    function  (data {        function  (i, item) {            $ ("Body"). Append (' );        });}    );

The server needs to return data samples like this:

Response.contenttype= "text/html; Charset=utf-8 "= request.querystring[" Callback "+" {\ "success\": [{\ "id\": 1, \ "title\": \ "title 1\"} {\ "id\": 2, \ "title\": \ "title 2\"}, {\ "id\": 3, \ "title\": \ "title 3\"}]} ");

2 Specifies the JSONP name, and the function that returns the name of the

// Here we have our own designation of JSONP's callback name . $.ajax ({    ' http://lifeloopdev.info/get_events ',    "Jsonp",    "offset=0& Num_items=10 ",    ' username ',    ' password ',    " Successcallback ",     ' Successcallback '}); function Successcallback (data) {    function  (i, item) {        $ ("Body"). Append (' 

); }

The server needs to return data samples like this:

Response.contenttype= "text/html; Charset=utf-8 "= request.querystring[" Successcallback "+" {\ "success\": [{\ "id\": 1, \ "title\": \ " Title 1\ "}, {\" id\ ": 2, \" title\ ": \" title 2\ "}, {\" id\ ": 3, \" title\ ": \" title 3\ "}]}");

3 Specifies the JSONP name, and does not specify functions that return function names

$.ajax ({    ' http://lifeloopdev.info/get_events ',    "Jsonp",    "offset=0& Num_items=10 ",    ' username ',    ' password ',    " Successcallback ",     function  (data) {        function  (i, item) {            $ ("Body"). Append (' );     });

The server needs to return data samples like this:

Response.contenttype= "text/html; Charset=utf-8 "= request.querystring[" Successcallback "+" {\ "success\": [{\ "id\": 1, \ "title\": \ " Title 1\ "}, {\" id\ ": 2, \" title\ ": \" title 2\ "}, {\" id\ ": 3, \" title\ ": \" title 3\ "}]}");

4 using Getjson () to get data

/* * * NOTE: * Here is the address called jsoncallback=? is the key! Which of our concerns is jsoncallback=? What role did it play? The original jsoncallback=? After being replaced, the method name is passed to the server. * What do we do on the server side? The server accepts the parameter Jsoncallback and returns the value of Jsoncallback as the JSON data method name. */ $.getjson (function  (data) {    function  (i, item) {        $ ("body"). Append (' );     });

The server needs to return data samples like this:

Response.contenttype= "text/html; Charset=utf-8 "= request.querystring[" Jsoncallback "+" {\ "success\": [{\ "id\": 1, \ "title\": \ "title 1\ "}, {\" id\ ": 2, \" title\ ": \" title 2\ "}, {\" id\ ": 3, \" title\ ": \" title 3\ "}]}");

Transferred from: http://www.cnblogs.com/yeminglong/archive/2013/06/24/3152976.html

Use of JSONP and callback

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.