javascript - 无法在 jquery ajax 中实现延迟承诺
问题描述
我正在努力实现延迟以获得异步 ajax 响应。我有这个设置:
报告.js
function getReport(ref)
{
$.ajax({
url: "report.php",
dataType: 'json',
data: {
ref: ref,
},
success: function(result){
return (result);
}
}
});
}
索引.html
<script>
function firstFunction() {
console.log ("start");
getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction();
alert(test);
</script>
目前我得到“未定义”立即返回,因为警报框不等待 ajax 函数运行。使用一些在线教程,我尝试以这种方式实现它:
报告.js
function getReport(ref)
{
var deferred = $.Deferred();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
ref: ref,
},
success: function(result){
deferred.resolve(result);
}
}
});
returned deferred.promise();
}
索引.html
<script>
function firstFunction() {
console.log ("start");
getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
$.when(getData()).done(function(value) {
alert(value);
});
getData().then(function(value) {
alert(value);
});
</script>
我显然在路上犯了一些错误,因为我得到了以下错误,我似乎无法克服它:
Uncaught SyntaxError: Unexpected identifier
index2.html:12 start
index2.html:13 Uncaught ReferenceError: getReport is not defined
at firstFunction (index2.html:13)
at index2.html:16
解决方案
我认为deferred
在 getReport 中添加对象是不必要的,因为$.ajax
已经为您创建了一个。以这种方式修改原始代码可能会更好:
function getReport(ref)
{
return $.ajax({ // Return the deferred object here. It is returned by .ajax()
url: "report.php",
dataType: 'json',
data: {
ref: ref,
} // Remove the callback here.
// You cannot call return in the way you're trying here.
// The context is different and outside of normal flow.
});
}
然后在您的索引文件中:
<script>
function firstFunction() {
console.log ("start");
// You must return the returned value here as well, otherwise variable `test` is going to be undefined.
return getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction(); // test is now a deferred object
test.done(function(data) {
alert(data);
});
</script>
推荐阅读
- html - 有人能告诉我为什么我的轮播导致我所有的文本元素都移动了吗?
- javascript - Qml上传文件(路径)
- oauth - JWT 令牌的一些“不验证发行者的后果”可能是什么?
- python - LSTM:将编码器的隐藏状态添加到解码器以提高性能
- json - 如何从Json文件中提取信息。必须通过类型映射Json结构并使用AESON
- codenameone - 代号一 android 构建失败
- java - 不使用泛型对观察者模式进行强制转换
- javascript - 查找日期范围内的工作日
- c# - TFException:期望 arg[0] 为字符串,但提供了浮点数 (Unity3d)
- python - Python 将字典列表视为字符串:如何解析?