ajax 'GET' call returns jsonp okay but callback produces 'undefined' data

妖精的绣舞 提交于 2019-12-07 14:26:16

问题


I'm accessing a cross-domain webservice utilizing an.ajax jquery call from an html page. While I can see the jsonp data using firebug, I am not able to load it into a variable or even display it (for debugging purposes). Attempts to retrieve data using the jsonpCallback, success and complete functions always result in 'undefined' / null data.

Ultimately, I need to save the data to variables. Any assistance will be greatly appreciated!

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

回答1:


In JSONP you must define your function in your code.

jsonpCallback must be the name of this function, not a function.

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

You do it like this :

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


来源:https://stackoverflow.com/questions/10320619/ajax-get-call-returns-jsonp-okay-but-callback-produces-undefined-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!