HtmlCode:
<ButtonType= "Button"Onclick= "Fun1 ()">Cross-origin access</Button><ScriptType= "Text/JavaScript"SRC= "Http://code.jquery.com/jquery-1.10.1.min.js"> </Script>
JS Code:
// Function jsoncallback (URL, callback) {$. getscript (URL, function () {callback (JSON) ;});} function fun1 () {jsoncallback ('HTTP: // mupicheng.com/js.php', function (JSON) {alert (JSON. message );})}
PHP file for cross-origin access:
<?PHP$ Ary=Array('Result' => 0, 'message' => 'cross-origin successfully');$ JSON= Json_encode ($ Ary);//The final JSON data output must be defined in this way, which utilizes the closure feature of Js.Echo"Var JSON =$ JSON;";?>
Note:
1: The jquery version must be later than version 1.2. Otherwise, cross-origin processing is not supported.
2: only get requests are supported.
3: The request URL must return data as shown in the following example.
Advantages and disadvantages of this solution:
Advantages:
1: The solution is simpler, more efficient, and clearer than the scheme of adding output parent. XXX () with IFRAME, And the frontend processing is more convenient.
2: The proxy method is much simpler in programming.
Disadvantages:
1: jquery is required,
2: The returned data format must be in the sample format. Of course, it is not limited to JSON, but it is the most convenient to process.
Get access to the instance:
<SCRIPT type = "text/JavaScript">FunctionFun1 () {$. Getjson ("http://a.com/c.php? No = 10 & MSG = OK & format = JSON & jsoncallback =? ",Function(Data) {alert (Data.MSG );});}</SCRIPT> <button type = "button" onclick = "fun1 ()"> Cross-origin processing </button>
C. php file:
<?PHP$ No=$ _ Get['No'];$ Msg=$ _ Get['Msg'];$ JSON= Json_encode (Array('No' =>$ No, 'Msg '=>$ Msg));//The following output is required:Echo $ _ Get['Jsoncallback']. '('.$ JSON.')';