jQuery AJAX跨域 [英] jQuery AJAX cross domain

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

问题描述

以下是两个网页:test.php和testserver.php。

Here are two pages, test.php and testserver.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);
?>

现在我的问题:当这两个文件都在同一台服务器,它工作, alert(Success)被调用;如果它在不同的服务器上,意味着webserver上的testserver.php和localhost上的test.php,它不工作,并且正在执行 alert(Error)。即使ajax中的网址已更改为 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).");";
?>

echo可能是错误的,从我做php以来已经有一段时间了。在任何情况下,你需要输出callbackName('jsonString')注意引号。

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.

正如Stefan Kendall发布的, $。getJSON()是一个简写方法,但是你需要将'callback =?'作为GET参数附加到url ,值是?,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天全站免登陆