【问题标题】:jsonp cross domain request response gives null while parsingjsonp跨域请求响应在解析时给出null
【发布时间】:2012-04-24 16:50:25
【问题描述】:

我尝试使用 jquery 发出跨域请求。这就是客户端的样子,

<script src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
    $.ajax({
        type: 'GET',
        url: "http://www.xserver.com/xdomainhandler.php",
        processData: true,
        data: {
            type:"gotohell"
        },
        dataType: "json",
        success: function (data) {
            myglob=data;
            var repo=JSON.parse(myglob);
            alert(repo.type);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown){
            alert('ends up in error state');

        }
    });
});
</script>  

接收此请求的服务器页面代码将如下所示:

<?php
header('Access-Control-Allow-Origin: *');  
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
session_cache_limiter('nocache');

$arr = array ('response'=>'success','comment'=>'test comment here','type'=>$_GET['type']);
echo json_encode($arr);
?>

但是当我完成请求/响应过程时,我在“repo”变量中什么也没有。我使用 firebug 检查了响应,它显示了类似的响应,

{"response":"success","comment":"test comment here","type":"gotohell"}

我还检查了它显示的萤火虫 DOM 面板中的 myglob 变量,

Object { response="success", comment="test comment here", type="gotohell"}

但是当我将 myglob 解析为 repo 时,它什么也没显示……我哪里出错了。有人可以帮助我吗?谢谢!

【问题讨论】:

    标签: jquery json cross-domain jsonp


    【解决方案1】:

    你不需要解析它,因为 jQuery 会为你解析它,所以避免

            var repo=JSON.parse(myglob);
    

    然后打电话

      alert(data.type);
    

    【讨论】:

    • 谢谢,它的工作。我明白了,所以如果我们将数据类型设置为 json,它会自动解析正确吗?
    • @Sekar 是的,如果你没有设置数据类型,jQuery 会尝试从标题中猜测它,如果它猜测它是一个 json,它会解析它,所以你永远不应该解析响应
    【解决方案2】:

    因为你提供了dataType: 'json' jQuery 已经解析了响应 - 再次解析它会导致错误。删除以下行:

    var repo = JSON.parse(myglob);
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2012-03-18
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      相关资源
      最近更新 更多