jquery cross-domain get a simple instance of JSON _jquery

Source: Internet
Author: User
Tags error handling script tag

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

The general cross-domain use of the two methods is: $.ajax and $.getjson

Finally, after careful silence, read the JSON official document and discover this paragraph:

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

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

Jquery has callback this parameter every time the request is sent across the domain, in fact the value of this parameter is the callback function name, so the server side should put this parameter to the front when sending the JSON data, the value of this parameter is often randomly generated, For example: jsonp1294734708682, you can also set the name of the callback method through the $.ajax method. After you understand the principle, the server side should send the data like this:

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

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

Now let's start with the example.

If the data returned normally:

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

Now let's introduce our own parameters to jquery.

/**
* @dataType (String) 
* "XML": Returns an XML document that can be processed with jQuery.
* "HTML": Returns plain text HTML information, and the included script tag executes when the DOM is inserted.
* "Script": Returns the plain text JavaScript code. "JSON": Returns JSON data.
* "JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? To 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 to replace the "callback=?" The "callback" section of the URL parameter in the GET or POST request,
* such as {jsonp: ' onjsonpload '} will cause the "onjsonpload=?" passed to the server. * *
@jsonpCallback (String)
* Specifies a callback function name for the JSONP request. \/** This value will be used to replace the random function name that jquery automatically generates.
* This is primarily used to allow jquery to generate unique function names, which makes it easier to manage requests and easily provides callback functions and error handling.
* You can also specify this callback function name when you want the browser to cache the GET request.
*/

1 does not specify the name of the JSONP,

$.ajax ({
  URL: ' http://lifeloopdev.info/get_events ',
  dataType: "Jsonp",
  data: "offset=0&num_items= ",
  Username: ' username ',
  password: ' Password ',
  success:function (data) {
    $.each (data.success, function (I, item) {
      $ ("Body"). Append ('  
 

The server needs to return data samples like this:

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 Specifies the name of the JSONP, and the function that returns the names of the functions,

Here we ourselves specify the name of the JSONP callback
$.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 samples like this:

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 Specifies the name of the JSONP, and does not specify a function that returns the name

$.ajax ({
  URL: ' http://lifeloopdev.info/get_events ',
  dataType: "Jsonp",
  data: "offset=0&num_items= ",
  Username: ' username ',
  password: ' Password ',
  jsonp:" Successcallback ",
  success:function (data) {
    $.each (data.success, function (I, item) {
      $ ("Body"). Append ('  
 

The server needs to return data samples like this:

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 get data,

/**
* Note:
* Here the address of the call jsoncallback=? is the key! Which of our concerns is jsoncallback=? What's the effect? Original jsoncallback=? is replaced, the method name is passed to the server.
* What do we do on the server side? The server accepts the parameter Jsoncallback and then returns 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 samples like this:

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 above jquery Cross-domain access to JSON is a simple example of the small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.