Simple Ajax cross-domain request

Source: Internet
Author: User

Recently encountered need for Ajax cross-domain requirements

First look at what kind of error will occur if you do not do any Ajax cross-domain requests that are handled specifically

Client code:

<script type= "Text/javascript" >    $.ajax ({        ' http://localhost/test/respone.php ',        ' Get ',        ' json ',        success:function  (res) {            console.log (res);        }    } );     </script>

Service-Side code:

<?phpecho Json_encode ([' name ' = ' ogq ', ' age ' =>18]);? >

Operation Result:

Tip: Failed to load http://localhost/test/respone.php:No ' Access-control-allow-origin ' header was present on the requested R Esource. Origin ' http://my.com ' is therefore not allowed access. Error

This is because the browser Ajax can not be caused by the cross-domain, the following is I find the data after a simple Ajax cross-domain request and return

Client code:

<script type= "Text/javascript" >    $.ajax ({        URL: ' http://localhost/test/respone.php ',        type: ' Get ',        dataType: ' Jsonp ',        success:function (res) {            console.log (res);        }    });    </script>

Yes, just the datatype: "JSON" changed to "Jsonp",

Then the server-side code:

<?phpecho $_request[' callback '], ' ('. Json_encode ([' name ' = ' ogq ', ' age ' =>18]), ') ';? >

At the request time, output results

So you can cross the domain normally.

PS: No drill down, can be used normally. Hee Hee

Simple Ajax cross-domain request

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.