我意识到这个问题被问了很多,通常答案是 AJAX 是异步的,这就是它返回未定义的原因,但即使我在这里将异步设置为 false,调用函数时它仍然返回未定义。 res 始终未定义
function sendRequest(link, type, query) {
$(document).ready(function(){
$.ajax({
'url' : link,
'type' : type,
'data' : query,
'async' : false,
'dataType': "json",
'headers': {
'Cache-Control':'max-age=0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
},
'success': function(data) {
var res = data;
}
});
});
return res;
}
此外,我确信请求已正确发送,并且响应也已正确接收
最佳答案
我认为更好的方法是让您的 sendRequest
函数返回 jQuery Promise Object 。举个例子
function sendRequest(link, type, query) {
return $.ajax({
'url' : link,
'type' : type,
'data' : query,
'dataType': "json",
'headers': {
'Cache-Control':'max-age=0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Type':'application/x-www-form-urlencoded',
'Accept-Language':'en-US,en;q=0.8,ar;q=0.6',
}
});
}
使用
sendRequest('/someurl', 'GET', {}).done(function(data) {
// do whatever you need with data here
});
关于javascript - jQuery ajax 函数未定义结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920175/