jQuery的AJAX跨域 [英] jQuery AJAX cross domain

查看:251
本文介绍了jQuery的AJAX跨域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是两页,test.php的和servertest.php。

Here are two pages, test.php and servertest.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

<?php
$arr = array("element1",
             "element2",
             array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>

现在我的问题:当这两个文件是在同一台服务器上(无论是本地主机或网络服务器),它的工作原理和警报(成功)被调用;如果是在不同的服务器上,这意味着testserver.php Web服务器和test.php的在本地主机,它不能正常工作,而警报(错误)正在执行。即使里面的AJAX的网址更改为<一个href="http://domain.com/path/to/file/testserver.php">http://domain.com/path/to/file/testserver.php

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; 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. Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php

推荐答案

使用 JSONP

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
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>

回声可能是错误的,它已经有一段时间,因为我做了PHP。在需要输出callbackName('jsonString)任何情况下,注意引号。 jQuery将通过它自己的回调名字,所以你需要得到从GET参数。

The echo might be wrong, it's been a while since I done php. In any case you need to output callbackName('jsonString') notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params.

和作为斯特凡·肯德尔发布, $ .getJSON()是一个速记方法,但你需要追加'回调=?到URL为GET参数(是的,价值是?,jQuery的替换这与它自己生成的回调方法)。

And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?' to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).

这篇关于jQuery的AJAX跨域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆