Solve Ajax cross-origin problems under the jquery framework

Source: Internet
Author: User

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.')';

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.