跨域ajax请求问题

时间:2013-04-15 05:42:39

标签: jquery asp.net ajax json jsonp

我需要从跨域获取json数据。

$.getJSON('http://xx.xx.xx.xx/SampleService/Handler.ashx?callback=?', data, function (jsonData) {
                alert('1');
            })
            .done(function () { console.log("second success"); })
            .fail(function () { console.log("error"); })
            .always(function () { console.log("complete"); });

处理程序代码:

context.Response.ContentType = "application/json";
                SampleService service = new SampleService();

                List<List<Byte>> response = service.GetData();
                string jsonData = JsonConvert.SerializeObject(response);
                context.Response.Write(string.Format("{0}([{1}]);", context.Request["callback"], jsonData));

错误,我得到的是:

"parsererror"
Error: jQuery19108131180874027861_1366004862133 was not called

3 个答案:

答案 0 :(得分:2)

关于此问题的好文章:Cross Domain AJAX

答案 1 :(得分:1)

使用jsonp调用进行跨域请求。使用类似这样的东西

$.ajax({
        url : "http://xx.xx.xx.xx/SampleService/Handler.ashx",
        type: "GET",
        dataType: "jsonp",
        jsonp : "callback",
        success: function(data) {alert("Success");},
        error: function(data) { alert("Error"); }

        });        
   });
在您的php页面上

返回结果

echo $_GET['callback'] . "($result)";exit;

其中$ result是你的json_encoded数组。

答案 2 :(得分:0)

你看到的jQuery19108131180874027861_1366004862133是一个自动生成的回调包装函数,当你没有指定回调函数时jQuery会附加它。即你有回调=?如果您可以访问正在调用的服务器端脚本,则可以将JSON包装在函数中,并使用JSONP调用它来解决跨域问题。即 - 将您的回调函数命名为jsonCallback。

服务器端脚本输出:

jsonCallback(
    {
        [insert your json code here]
    }
);

然后是客户方:

(function($){ var url ='http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    done: function(json) {
       console.dir(json);
    },
    fail: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

进一步阅读:JQUERY’S JSONP EXPLAINED WITH EXAMPLES

相关问题