我正在使用HTML页面中的an.ajax jquery调用来访问跨域Web服务。虽然我可以使用firebug看到jsonp数据,但我无法将其加载到变量中甚至无法显示出来(出于调试目的)。尝试使用jsonpCallback,成功和完成函数检索数据始终会导致“未定义” /空数据。

最终,我需要将数据保存到变量中。任何协助将不胜感激!

$.ajax({
    data: {
        User: UserValue,
        GUID: GUIDValue
    },
    cache: false,
    dataType: "jsonp", // tried json
    type: "GET",
    crossDomain: true,
    jsonp: false,  // tried true
    jsonpCallback: function (saveData) {
        if (saveData == null) {
            alert("DATA IS UNDEFINED!");  // displays every time
        }
        alert("Success is " + saveData);  // 'Success is undefined'
    },
    url: "http://localhost/NotifMOD/NotifService.svc/GetAllMessages?callback=success?",
    async: false, // tried true
    error: function (XMLHttpRequest, textStatus, errorThrown) {
         console.log(textStatus, errorThrown);
    },
    complete: function (a, b) {
        alert(a); //[object Object]
        alert(b); // parseerror
    }
});

最佳答案

在JSONP中,您必须在代码中定义函数。

jsonpCallback必须是此函数的名称,而不是函数。

http://api.jquery.com/jQuery.ajax/

你这样做:

function receive(saveData) {
    if (saveData == null) {
            alert("DATA IS UNDEFINED!");  // displays every time
    }
    alert("Success is " + saveData);  // 'Success is undefined'
}

$.ajax({
    data: {
        User: UserValue,
        GUID: GUIDValue
    },
    cache: false,
    dataType: "jsonp", // tried json
    type: "GET",
    crossDomain: true,
    jsonp: false,  // tried true
    jsonpCallback: "receive",
    url: "http://localhost/NotifMOD/NotifService.svc/GetAllMessages?callback=receive?",
    async: false, // tried true
    error: function (XMLHttpRequest, textStatus, errorThrown) {
         console.log(textStatus, errorThrown);
    }
});

关于jquery - ajax'GET'调用返回jsonp可以,但是回调会产生'undefined'数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10320619/

10-10 01:21
查看更多