ajax调用的alert-ing返回值
(1. 你觉得拥有一个可以调用 ajax(url,data,async)
的全局 jQuery ajax “助手”有用吗?)
function ajax(ajax_url, ajax_data, ajax_async){
ajax_async = typeof(ajax_async) != 'undefined' ? ajax_async : true;
$.ajax({
type: 'GET',
url: ajax_url,
data: ajax_data,
async: ajax_async,
dataType: 'text',
success: function(response) {
return response;
},
error: function(){
}
});
}
如果我调用一个放置 GET 和返回成功响应。
alert(ajax('localhost/hello','',false);
如果我执行alert(get_ajax())
,我会收到“未定义”的警报。即使有返回值,
我也会看到它的事件循环问题,但我async:false< /code> 在 ajax 调用中。想法?
(1. Do you find it useful to have a global jQuery ajax 'helper' that you can call ajax(url,data,async)
? )
function ajax(ajax_url, ajax_data, ajax_async){
ajax_async = typeof(ajax_async) != 'undefined' ? ajax_async : true;
$.ajax({
type: 'GET',
url: ajax_url,
data: ajax_data,
async: ajax_async,
dataType: 'text',
success: function(response) {
return response;
},
error: function(){
}
});
}
If I'm calling a function that places a GET and returns the success response.
alert(ajax('localhost/hello','',false);
If I do alert(get_ajax())
I get an alert of 'undefined'.. even if there was a return value
I see its an event loop issue, but I async:false
in the ajax call. thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于同步调用,我相信你会这样做
For an synchronous call, I believe you would do
您的
ajax
函数包装了$.ajax
调用,但不返回任何内容:这就是undefined
的来源。要在alert
示例中获取一些值,您应该在函数底部添加 return 语句。要获得带有响应的警报,应执行以下操作:
Your
ajax
function wraps the$.ajax
call, does doesn't return anything: that's where theundefined
comes from. To get some value in youralert
example, you should add a return statement at the bottom of your function.To get an alert with the response, the following should do:
这是已经被问过一百万次的问题之一,但几乎不可能搜索到。不管怎样,问题是当你从这里返回时......
你不是从
ajax()
函数返回,而是从匿名success
函数返回。要从主函数返回值,您必须将字符串保存到变量中,以便可以从正确的函数返回。请注意,这仅在您进行同步调用时才有效。对于异步调用,最好提供回调函数作为参数并将其用作成功函数。
This is one of those questions that has been asked a million times, but it's nearly impossible to search. Anyway, the problem is that when you return from here...
...you're not returning from the
ajax()
function but the anonymoussuccess
function. To return the value from the main function you have to save the string to a variable so that you can return from the correct function.Note that this only works when you're making a synchronous call. For asynchronous calls it's better to give a callback function as an argument and use it as the success function.