3

我有以下功能很好,我使用 JSONP 来克服跨域,编写了一个 http 模块来更改内容类型,并且没有在 url 中附加回调名称。

function AddSecurityCode(securityCode, token) {
var res=0;
$.ajax({ url: "http://localhost:4000/External.asmx/AddSecurityCode",
    data: { securityCode: JSON.stringify(securityCode),
        token: JSON.stringify(token)
    },
    dataType: "jsonp",
    success: function(json) {
        alert(json); //Alerts the result correctly
        res = json;
    },
    error: function() {
        alert("Hit error fn!");
    }
});
return res; //this is return before the success function? not sure.

}

res 变量总是未定义。而且我不能将 async=false 与 jsonp 一起使用。那么我怎样才能将结果返回到函数外部呢?我当然需要为后续调用这样做。

请指教,谢谢。问题是我不能在这个函数之外返回结果值

4

3 回答 3

7

你根本无法做到这一点。

您必须重写您的代码流,以便AddSecurityCode接受一个callback参数(即要运行的函数),然后在您的成功回调中调用该参数:

function AddSecurityCode(securityCode, token, callback) {

    $.ajax({
        ....
        success: function(json) {
            alert(json); //Alerts the result correctly
            callback(json); // HERE BE THE CHANGE
        }
        ....
    });
}
于 2009-08-27T15:30:23.977 回答
0

将 async: false 添加到 ajax 请求对象

$.ajax({
   ...
   async: false,
   ...
});
return res;

但不推荐这样做,因为它会阻塞浏览器,并且在 ajax 调用完成之前会被视为没有响应。异步进程应该使用回调函数,就像提到的其他答案一样

于 2014-05-02T01:13:37.477 回答
0

您在函数内部声明了 res ,使其成为该函数的本地范围。所以有一个开始。在函数外声明 res 看看会发生什么。

于 2009-08-27T17:36:33.350 回答