A simple example of Jquery cross-origin to obtain Json, jquery cross-origin json

Source: Internet
Author: User

A simple example of Jquery cross-origin to obtain Json, jquery cross-origin json

In the past two days, when using Jquery to retrieve data across domains, I often encounter the invalid label error, which is very depressing and cannot retrieve the json value sent back by the server,

Generally, two cross-origin methods are used: $. ajax and $. getJSON.

Finally, take a closer look and read the official json document to find the following paragraph:

JSON data is a structured data that can be easily parsed using JavaScript. If the obtained data file is stored on a remote server (the domain name is different, that is, cross-Origin data retrieval), The jsonp type is required. If this type is used, a query string parameter callback =? will be created? This parameter is added after the request URL. The server should add the callback function name before the JSON data to complete a valid JSONP request. If you want to specify the callback function parameter name to replace the default callback, you can set the jsonp parameter of $. ajax.

In fact, the cross-origin principle of jquery is implemented through the external chain <script>, and then the callback function parameters are added to realize the real cross-origin.

Jquery will have the callback parameter each time it sends a request across domains. In fact, the value of this parameter is the name of the callback function. Therefore, when sending json data, the server should put this parameter in front, the value of this parameter is often randomly generated, for example, jsonp129472138682. You can also use $. set the name of the callback method in ajax. After understanding the principles, the server should send data as follows:

string message = "jsonp1294734708682({\"userid\":0,\"username\":\"null\"})";

In this way, json data {\ "userid \": 0, \ "username \": \ "null \"} is used as a parameter of the jsonp129472138682 callback function.

Let's start the instance.

If the data is returned normally:

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

Next we will introduce jquery's own parameters.

/*** @ DataType (String) * "xml": returns the XML document, which can be processed by jQuery. * "Html": returns plain text HTML information. The script tag is executed when the dom is inserted. * "Script": returns plain text JavaScript code. "Json": Return JSON data. * "Jsonp": JSONP format. When calling a function in the form of JSONP, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function. * "Text": returns a plain text String * // *** @ jsonp (String) to rewrite the name of the callback function in a jsonp request. * This value is used to replace "callback =? "Callback" in the URL parameter of this GET or POST request. * For example, {jsonp: 'onjsonpload'} causes "onJsonPLoad =? "To the server. * // *** @ JsonpCallback (String) * specifies a callback function name for the jsonp request. This value is used to replace the random function name automatically generated by jQuery. * This function is mainly used to make jQuery generate a unique function name, which makes it easier to manage requests and conveniently provide callback functions and error handling. * You can also specify the callback function name when you want the browser to cache the GET request. */

1. do not specify the jsonp name,

$.ajax({  url: 'http://lifeloopdev.info/get_events',  dataType: "jsonp",  data: "offset=0&num_items=10",  username: 'username',  password: 'password',  success: function (data) {    $.each(data.success, function (i, item) {      $("body").append('

The server needs to return data as follows:

Response.ContentType="text/html; charset=utf-8";String callback = Request.QueryString["callback"].ToString();Response.Write(callback + "{ \"success\": [{ \"id\": 1, \"title\": \"title 1\" }, { \"id\": 2, \"title\": \"title 2\" }, { \"id\": 3, \"title\": \"title 3\"}] }");

2. Specify the jsonp name and the function,

// Here we specify the jsonp callback name $. ajax ({url: 'http: // lifeloopdev.info/get_events', dataType: "jsonp", data: "offset = 0 & num_items = 10", username: 'username', password: 'Password', jsonp: "successCallback", jsonpCallback: 'successcallback'}); function successCallback (data) {$. each (data. success, function (I, item) {$ ("body "). append ('

The server needs to return data as follows:

Response.ContentType="text/html; charset=utf-8";String callback = Request.QueryString["successCallback"].ToString();Response.Write(callback + "{ \"success\": [{ \"id\": 1, \"title\": \"title 1\" }, { \"id\": 2, \"title\": \"title 2\" }, { \"id\": 3, \"title\": \"title 3\"}] }");

3. Specify the jsonp name. do not specify the function,

$.ajax({  url: 'http://lifeloopdev.info/get_events',  dataType: "jsonp",  data: "offset=0&num_items=10",  username: 'username',  password: 'password',  jsonp: "successCallback",  success: function (data) {    $.each(data.success, function (i, item) {      $("body").append('

The server needs to return data as follows:

Response.ContentType="text/html; charset=utf-8";String callback = Request.QueryString["successCallback"].ToString();Response.Write(callback + "{ \"success\": [{ \"id\": 1, \"title\": \"title 1\" }, { \"id\": 2, \"title\": \"title 2\" }, { \"id\": 3, \"title\": \"title 3\"}] }");

4. Use getJSON () to obtain data,

/*** Note: * jsoncallback =? Is the key! Among them, we are concerned about jsoncallback =? What role does it play? Originally, jsoncallback =? After the method is replaced, the method name is passed to the server. * What do we do on the server? The server must accept the jsoncallback parameter, and then return the jsoncallback value as the JSON data method name. */$. getJSON ("http: // 192.168.20.86/friend/getMyJsonData. aspx? Jsoncallback =? ", Function (data) {$. each (data. success, function (I, item) {$ ("body "). append ('

The server needs to return data as follows:

Response.ContentType="text/html; charset=utf-8";String callback = Request.QueryString["jsoncallback"].ToString();Response.Write(callback + "{ \"success\": [{ \"id\": 1, \"title\": \"title 1\" }, { \"id\": 2, \"title\": \"title 2\" }, { \"id\": 3, \"title\": \"title 3\"}] }");

The simple example of Jquery's cross-domain Json acquisition above is all the content shared by Alibaba Cloud xiaobian. I hope you can give us a reference and support for the help house.

Related Article

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.