0

我在使用 Jquery ajax 函数执行跨域 REST 调用时遇到了很多麻烦。

这是代码:

 $.ajax({
            url: restUrl,
                type: 'GET',
                crossDomain : true,
                dataType: 'jsonp',
                jsonp: false,
                jsonpCallback: 'jsonpCallbackTest',
                error: function(xhr, status, error) {
                    console.log('not OK '+xhr);
                    console.log('not OK '+status);
                    console.log('not OK '+error);
                },
                success: function(jsonp) {
                    alert("success");
                }
            });

这就是我在 Firebug 控制台中得到的:

不正常 [object Object] Init.js:872
不正常 parsererror Init.js:873
不正常 错误:未调用 jsonpCallbackTest


我究竟做错了什么?

关于 Matej

4

1 回答 1

4

我究竟做错了什么?

从您在问题中提供的代码信息很难说。可能有很多原因。例如,您尝试调用的远程 REST Web 服务返回 JSON 响应而不是 JSONP。

此外,您似乎已经定义了该jsonpCallbackTest函数,但您使用的是不兼容的匿名成功处理程序。试试这样:

$.ajax({
    url: restUrl,
    type: 'GET',
    jsonpCallback: 'jsonpCallbackTest',
    error: function(xhr, status, error) {
        console.log('not OK '+xhr);
        console.log('not OK '+status);
        console.log('not OK '+error);
    }
});

然后定义 jsonpCallbackTest 函数:

function jsonpCallbackTest(jsonp) {
    alert("success");
}

您还必须查看远程 Web 服务的文档如何指定 JSONP 回调。是否可以将其作为查询字符串参数传递。

通常最好让 jQuery 将随机回调函数名称传递给 Web 服务:

$.ajax({
    url: restUrl,
    type: 'GET',
    dataType: 'jsonp',
    success: function(json) {
        alert("success");
    },
    error: function(xhr, status, error) {
        console.log('not OK '+xhr);
        console.log('not OK '+status);
        console.log('not OK '+error);
    }
});
于 2012-07-04T07:44:44.610 回答