Client:
Using $.getjson () when transferring the first parameter, that is, the URL, if a cross-domain request must have a parameter with a value of "?", such as:
The code is as follows |
Copy Code |
$.getjson ( "Http://202.196.35.41/json.php?callback=?", function (data) { alert (data); } }; |
jquery will send this "?" when it sends a request. Replace with a unique string, as shown below
and declare a variable with the same name as this string, and assign the passed-in callback function to the variable.
Service side:
The server must be a dynamic program, can not be static text files, because the server to receive the passed function name, is the above figure callback value jquery172031288272701203823_1344179936251.
The server then constructs a function-calling string that takes the value that needs to be sent to the client as a parameter.
That is: jquery172031288272701203823_1344179936251 ([here Pass parameter JSON data]).
On the PHP code.
The code is as follows |
Copy Code |
<?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). ') '; |
Ajax-derived data:
jquery172031288272701203823_1344179936251 ([{"id": 1, "name": "admin"},{"id": 2, "name": "Root"}]) the client gets this data and executes the statement. The Passed-in function is called and the data is passed in, because the same function name has been specified in the return function passed in by $.getjson ().
The specific Cross-domain request is to take advantage of the nature of the JS file in the page that can introduce other domains, create a script node in the page, and point his src attribute to the dynamic file of the other domain. The browser loads the file and executes the script in it.