Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

javascript - jQuery AJAX跨域(jQuery AJAX cross domain)

Here are two pages, test.php and testserver.php.(这是两个页面,test.php和testserver.php。)

test.php(test.php的) <script src="scripts/jq.js" type="text/javascript"></script> <script> $(function() { $.ajax({url:"testserver.php", success:function() { alert("Success"); }, error:function() { alert("Error"); }, dataType:"json", type:"get" } )}) </script> testserver.php(testserver.php) <?php $arr = array("element1", "element2", array("element31","element32")); $arr['name'] = "response"; echo json_encode($arr); ?> Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called;(现在我的问题是:当这两个文件都在同一台服务器(本地主机或Web服务器)上时,它会工作,并且会调用alert("Success") ;) If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing.(如果它位于不同的服务器上,意味着Web服务器上的testserver.php和localhost上的test.php,它不起作用,并且正在执行alert("Error") 。) Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php(即使ajax中的URL更改为http://domain.com/path/to/file/testserver.php)   ask by Firose Hussain translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use JSONP .(使用JSONP 。)

jQuery:(jQuery的:) $.ajax({ url:"testserver.php", dataType: 'jsonp', // Notice! JSONP <-- P (lowercase) success:function(json){ // do stuff with json (in this case an array) alert("Success"); }, error:function(){ alert("Error"); } }); PHP:(PHP:) <?php $arr = array("element1","element2",array("element31","element32")); $arr['name'] = "response"; echo $_GET['callback']."(".json_encode($arr).");"; ?> The echo might be wrong, it's been a while since I've used php.(回声可能是错的,自从我使用php以来已经有一段时间了。) In any case you need to output callbackName('jsonString') notice the quotes.(在任何情况下,您需要输出callbackName('jsonString')注意引号。) jQuery will pass it's own callback name, so you need to get that from the GET params.(jQuery将传递它自己的回调名称,因此你需要从GET参数中获取它。) And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?'(正如Stefan Kendall 所说$ .getJSON()是一种速记方法,但是你需要追加'callback=?') to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).(作为GET参数的url(是的,值是?,jQuery用它自己生成的回调方法替换它)。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...