【问题标题】:ajax 'GET' call returns jsonp okay but callback produces 'undefined' dataajax 'GET' 调用返回 jsonp 正常,但回调产生 'undefined' 数据
【发布时间】:2012-04-25 17:18:45
【问题描述】:

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

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

$.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
    }
});

【问题讨论】:

    标签: jquery get jsonp


    【解决方案1】:

    在 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);
        }
    });
    

    【讨论】:

    • 感谢“dystroy”的回复。我尝试了您的建议(除了将 URL 更改为 _http://localhost/NotifMOD/NotifiService.svc/GetAllMessages?callback=jsonpCallback?)。现在错误函数:'errorThrown' 参数返回“错误:未调用接收。
    • 函数名(这里是“receive”)必须是jsonp答案开头的那个。我的代码中有错误(假设服务器使用“回调”参数)。网址应以“callback=receive”结尾。
    • 也许它会帮助你:我制作的开源代码。客户端:github.com/Canop/braldop/blob/master/chrome/braldop/… 和服务器:github.com/Canop/braldop/blob/master/go/src/braldopserver/…
    • @Jake 这个答案来自 2012 年,那时 JSONP 仍然有意义。现在是 2017 年,JSONP 已经死了。如果您发现某个 API 要求您使用 JSONP,请使用其他 API。
    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 2013-06-17
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多