如何在函数外部返回 JSONP 调用的结果?
我有以下功能,效果很好,我使用 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 一起使用。 那么如何将结果返回到函数外部呢? 我确实需要为后续调用执行此操作。
请指教,谢谢。 问题是我无法在该函数之外返回结果值
I have the following function which works great, i used JSONP to overcome cross-domain, wrote an http module to alter the content-type and didn't append a callback name in the 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.
}
the res variable is alwayes comes undefined. and i can't use async=false with jsonp.
so how can i return the result to outside the function??
and i sure need to do that for subsequant calls.
Please advice, thanks.
The problem is i can't return the result value outside this function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你根本无法做到这一点。
你必须重写你的代码流程,以便
AddSecurityCode
接受一个callback
参数(即要运行的函数),然后您可以在您的成功回调中调用该参数:You simply cannot do this.
You have to rewrite your code flow so that
AddSecurityCode
takes acallback
parameter (i.e. a function to run) that you then invoke inside your success callback:您在函数内部声明了 res,使其成为该函数的本地作用域。所以有一个开始。在函数外部声明 res 并看看会发生什么。
You have res declared inside the function, making it's scope local to that function. So there's a start. Declare res outside the function and see what happens.
将 async: false 添加到 ajax 请求对象
,但不建议这样做,因为它会阻止浏览器,并且在 ajax 调用完成之前将被视为不响应。异步进程应该使用回调函数,就像提到的其他答案一样
Add async: false to the ajax request object
But this is not recommended since it will block the browser and will seen as not responding until the ajax call completed. Async process should use callback function like the other answer mentioning