Javascript ajax承诺不';在jquery中不返回任何值
我的剧本:Javascript ajax承诺不';在jquery中不返回任何值,javascript,jquery,ajax,Javascript,Jquery,Ajax,我的剧本: var testApp = (function($){ var data = [{ "layout": "getSample", "view": "conversations", "format": "json", }]; var Data = 'default'; function ajaxCall(opt) { return new Promise(function(resolv
var testApp = (function($){
var data = [{
"layout": "getSample",
"view": "conversations",
"format": "json",
}];
var Data = 'default';
function ajaxCall(opt) {
return new Promise(function(resolve, reject) {
jQuery.ajax({
method: "POST",
url: localStorage.getItem("root")+"/index.php",
"data": opt,
error: function() {
alert('error');
},
success: function(result) {
console.debug(result);
resolve(result);
}//end success
});//end ajax
});//end promise
}
return {
render: function(opt) {
if(typeof opt === 'object') {
var list = {
data : [opt]
}
//here I'm passing list object's data to be used in ajaxCall function.That's the reeason I used call method. It's data is passed from another page.
ajaxCall.call (list, list.data).then(function(v) {
console.log("v "+v); // nothing happens yet...expecting for the success object to be passed here
}).catch(function(v) {
//nothing to do yet
});
}
}
};//end return
})(jQuery);
在ajax中使用promise的正确方法是什么
ajaxCall.call (list, list.data).then(function(v) {
console.log("v "+v); // doesn't return anything
}).catch(function(v) {
//nothing to do yet
});
参考:嗯,这是我找到的一个简单的解决方法。。 //在代码行的下面,移到返回新承诺的上面,它就成功了
var opt=jQuery.extend({},数据[0],opt[0]) jqueryajax函数已经返回了承诺。你不必手动将它们变成承诺
var testApp = (function($) {
var ajaxDefaults = {
"layout": "getSample",
"view": "conversations",
"format": "json",
};
// this can be re-used in all your Ajax calls
function handleAjaxError(jqXhr, status, error) {
console.error('Ajax error', error);
});
function ajaxCall(opt) {
var url = localStorage.getItem("root") + "/index.php",
data = jQuery.extend({}, ajaxDefaults, opt);
return $.post(url, data).fail(handleAjaxError);
}
return {
render: function(opt) {
return ajaxCall(opt).then(function (result) {
console.log("v " + result);
return result;
});
}
};
})(jQuery);
- 您不需要使用
来调用函数。在这种情况下也没有多大意义。如果它不是一个对象方法,而是一个独立函数,请正常调用它并传递参数.call()
- 不能保证
包含任何值,但您的代码忽略了这种可能性。那是一只虫子localStorage.getItem(“root”)
- 代码中不需要两个变量
和data
。不要像这样设置跳闸线data
- 当
/$时,不需要使用
。post()$.ajax()
可以在一行中完成工作$。get()
- 从
方法及其render()
处理程序中返回一些内容,这样您就可以在应用程序的其他地方链接更多的代码,例如.then()
app.render({data: 1234}).then(function (result) { // ... });
jQuery.ajax()
已经返回承诺。除此之外,还不清楚您的代码应该实现什么。请从正确缩进开始,并添加一个关于其目的、您预期会发生什么以及会发生什么的解释。还要删除未使用的代码,如注释掉的for循环代码。要么你需要一行代码,要么你不需要-下定决心。@Tomalak,我下定决心编辑了代码。看看你是否能回答太糟糕了,这一行不再存在于你问题的代码中。另外,您应该再次考虑我上面评论中的第一句话:jQuery.ajax()
已经返回了承诺。