The tutorials on the Internet are provided with an example. I don't know where to use $. getJSON to implement cross-origin Ajax. After some time of "research", I will write down the results.
Client:
When $. getJSON () is used to transmit the first parameter, that is, url, a cross-origin request must have a parameter value of "?". For example:
Copy to ClipboardReference: [www.bkjia.com] $. getJSON (
"Http: // 202.196.35.41/json. php? Callback =? ",
Function (data ){
Alert (data );
}
};
When jQuery sends a request, Replace it with a unique string, such
Declare a variable with the same name as this string, and assign the passed-back function to this variable.
Server:
The server must be a dynamic program, not a static text file, because the server must receive the passed function name, that is, the callback value in jquery172031288272701203823_1344179936133.
The server constructs a function call string and uses the value sent to the client as the parameter.
That is, jquery172031288272701203823_1344179936.pdf ([here, the parameter JSON data is transmitted]).
PHP code.
Copy to ClipboardReference: [www.bkjia.com] <? Php
Header ('content-Type: text/javascript; charset = UTF-8 ');
Class User {
Public $ id;
Public $ name;
Public function _ construct ($ id, $ name ){
$ This-> id = $ id;
$ This-> name = $ name;
}
}
$ Users = array (new User (1, 'admin'), new User (2, 'root '));
Echo $ _ REQUEST ['callback']. '('. json_encode ($ users ).')';
Data obtained by Ajax:
Copy to ClipboardReference: [www.bkjia.com] jquery172031288272701203823_1344179936133 ([{"id": 1, "name": "admin" },{ "id": 2, "name ": "root"}])
The client executes this statement after obtaining the data. if the same function name is specified for the callback function passed in by getJSON (), the incoming function is called and the data is passed in.
The specific cross-origin request utilizes the js file nature that can be introduced to other domains in the page, and creates a script node on the page to direct its src attribute to dynamic files in other domains. The browser will load the file and execute the script.
Comments:
This is JSONP, which generally does not need to be so troublesome. You can set ype: "jsonp". By default, the callback =? Add. You need to say hello only when you do not name the callback function parameter callback, for example, myOwnCallbackFunctionName = ?.