JQUERY/JS Ajax 4 ways to cross-domain

Source: Internet
Author: User
Tags getscript php code


About Ajax Cross-domain problem, sorted out today, in fact, there are other ways, personally recommended the following 4 kinds. Please refer to: Ajax cross-domain instance
One, the traditional Ajax method

1,js Code

$ ("#ajax"). Click (function () {
$.ajax ({
Type: "POST",
URL: "/test2.php",
Data: ' Name=ajax ',
DataType: "JSON",
Success:function (data) {
$ (' #Result '). Text (data.name);
}
});
});

2,test2.php Code

<?php
Header ("access-control-allow-origin:http://blog.51yip.com"); Allow blog.51yip.com to submit access
Header ("access-control-allow-origin:*"); Allow any access
echo Json_encode ($_post);

Second, Ajax Jsonp

$ ("#jsonp"). Click (function () {
$.ajax ({
URL: ' http://manual.51yip.com/test1.php ',
Data: {name: ' Jsonp '},
DataType: ' Jsonp ',
JSONP: ' Callback ',//The parameters prepared for the service side
Jsonpcallback: ' GetData ',//callback function
Success:function () {
Alert ("Success");
}
});
});

function GetData (data) {
$ (' #Result '). Text (data.name);
}

2,test1.php


<?php
if (isset ($_get[' name ')) && isset ($_get[' callback '))//callback root JS end to correspond, or it will be an error
{
Echo $_get[' callback ']. ' ('. Json_encode ($_get).   ');'; The format is fixed, why is this, not clear
}
?>

Three, $.getjson


$ ("#getjson"). Click (function () {
$.getjson (' http://manual.51yip.com/test1.php?name=getjson&callback=? ', function (data) {//No callback function, direct processing
$ (' #Result '). Text (data.name);
});
});

Four, $.getscript

$ ("#getscript"). Click (function () {
$.getscript (' Http://manual.51yip.com/test1.php?name=getscript&callback=getdata '); callback function root Jsonp the same
});

can also see the example source code, to view the JS

Related Article

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.