JSON (optional) and script labels are used to solve cross-origin Ajax problems. XMLHttpRequest of Ajax cannot be used for cross-origin because of JS security issues.
However, <SCRIPT> </SCRIPT> can use src = "http://otherSite.com/a.js" can be cross-origin, so dynamic writing to a <SCRIPT> </SCRIPT> is OK, SCR points to a file of other sites, for example,. PHP? Id = 15
Let A. php echo () a json string JSON reference: http://www.json.org/(optional)
<SCRIPT>
VaR element = Document. createelement ("script ");
Function createscript (COMPID, dataid ){
Element. src = "http://othersite.com/json.php? Comp_id = "+ COMPID +" & data_id = "+ dataid + "";
Element. type = "text/JavaScript ";
Element. Language = "JavaScript ";
}
Function writecontent (){
Alert (productjson. Product [0]. Name );
}
Window. onload = function (){
Createscript (1, 2 );
Document. getelementsbytagname ("head") [0]. appendchild (element );
}
If (document. All ){
Element. onreadystatechange = function () {// use IE
VaR state = element. readystate;
If (State = "loaded" | state = "interactive" | state = "complete "){
Writecontent ();
}
};
} Else {
Element. onload = function () {// FF
Writecontent ();
};
}
</SCRIPT>
The following is the JSON. php echo content.
VaR productjson = {'product ':[
{'Name': 'object name 1 '},
{'Building ': 'Building name 1 '},
{'Address': '5 '}
]
};
If jquery is used. Cross-origin problems are easier to solve.
$. Getjson (
"A. php? Callback =? ",
Function (data ){
Alert ("Callback data:" + data );
}
);
Callback =? For cross-origin calls, jquery will return a return value of jsonp instead '? ', In fact, it should be similar to' & callback = jsonp12126279 '. Therefore, the callback parameters must be intercepted in the background script and added before the original JSON. (It can be understood as a verification process ).
PHP:
$ Callback = $ _ Get ['callback'];
Echo $ callback. '('. json_encode (Array (key1 => value1, key2 => value2). ')'; // note the format
The returned result is 'json12126279 {key1: value1; key2: value2 }'