我正在使用jQuery的AJAX发送HTTP请求,但它没有返回值。
我创建了一个处理请求的Http对象,并创建了一个request()方法,该方法应该返回从请求中获取的内容。
class Http
constructor(url,type = 'GET') {
this.url = url,
this.type = type;
}
request() {
let response = '';
$.ajax({
'url': this.url,
'type': this.type,
dataType: 'json',
success: (data) => {
response = data
// console.log(data) - **works**
// return data - **doesn't work**
},
error: (error) => {
response = data;
}
});
return response;}
答案 0 :(得分:0)
AJAX请求本质上是异步,因此,您不知道何时完成。为了解决此问题,使用了回调功能。请求完成后将调用此回调。 (有一个成功的回调和一个错误的回调。)
http.request(...);
// Here, the ajax request is not completed yet.
您无法同步返回调用结果,因此必须在回调函数中使用它。
$.ajax({
'url': this.url,
'type': this.type,
dataType: 'json',
success: (data) => {
// use the response here only
},
error: (error) => {
// Handle errors here
}
});
如果您在回调中return
,则return
用于回调函数,而不是封闭函数。
您可以,但是您不应同步进行ajax调用。将参数添加到您的ajax调用中:
$.ajax({
'url': this.url,
'type': this.type,
dataType: 'json',
async: false, // Add this
success: (data) => {
// use the response here only
},
error: (error) => {
// Handle errors here
}
});
以这种方式不进行推荐,因为它会冻结您的应用程序,直到您得到答复为止。