jQuery AJAX 跨域 [英] jQuery AJAX cross domain

查看:25
本文介绍了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);
?>

现在我的问题:当这两个文件在同一台服务器(本地主机或 Web 服务器)上时,它可以工作并且 alert("Success") 被调用;如果它在不同的服务器上,意味着 web 服务器上的 testserver.php 和本地主机上的 test.php,它不工作,并且 alert("Error") 正在执行.即使 ajax 里面的 URL 改为 http://domain.com/path/to/文件/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've used 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天全站免登陆