I have studied cross-origin Ajax today. I have provided an example for all the tutorials on the Internet. I don't know how to use $. what is the key to implementing cross-origin Ajax in getjson? After a period 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:
1 $.getJSON(2 "http://202.196.35.41/json.php?callback=?",3 function(data){4 alert(data);5 }6 };
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.
1 <?php 2 header('Content-Type:text/javascript; charset=utf-8'); 3 class User{ 4 public $id; 5 public $name; 6 public function __construct($id, $name){ 7 $this->id = $id; 8 $this->name = $name; 9 }10 }11 $users = array(new User(1, 'admin'), new User(2, 'root'));12 13 echo $_REQUEST['callback'].'('.json_encode($users).')';
Data obtained by Ajax:
jQuery172031288272701203823_1344179936251([{"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.