Javascript jQuery$.when()和ajax调用
对于如何等待ajax返回值,然后再做一些事情,我有点困惑。以下是我尝试的:Javascript jQuery$.when()和ajax调用,javascript,jquery,ajax,Javascript,Jquery,Ajax,对于如何等待ajax返回值,然后再做一些事情,我有点困惑。以下是我尝试的: $('.project-item').on('click', function(){ var id = $(this).attr('id'); $.when(getImages(id)).done(function(resp) { console.log(resp.responseJSON); }); }); function getImages(id) { var data = { '
$('.project-item').on('click', function(){
var id = $(this).attr('id');
$.when(getImages(id)).done(function(resp) {
console.log(resp.responseJSON);
});
});
function getImages(id) {
var data = {
'action' : 'getImages',
'id' : id,
};
var result = $.Deferred();
result.resolve($.post(ajaxurl, data));
return result.promise();
}
但是console.log(resp.responseJSON)代码>立即返回未定义
ajax调用之前已经过测试,现在正在返回结果。您可以使用普通的旧JavaScript实现这一点
// define a function to handle a fetch Response as JSON.
const handleAsJson = response => response.json();
// Get a reference to your element
const item = document.querySelector('.project-item');
// Set up the click listener
item.addEventListener('click', async function onClickItem(event) {
// Initialize the fetch request with your data
const id = this.getAttribute('id');
const method = 'POST';
const action = 'getImages';
const body = JSON.stringify({ id, action });
// Send the fetch request and handle it as JSON
const resp = await fetch(ajaxurl, { method, body })
.then(handleAsJson)
// finally, log the result
console.log(resp)
});
请参见您不需要$.when
或$.Deferred()
,因为jQuery ajax方法已经返回了一个Deferred/promise对象
var ajaxurl='1〕https://my-json-server.typicode.com/typicode/demo/posts'
$('project item')。在('click',function()上{
var id=$(this.attr('id');
getImages(id).done(函数resp){
console.clear();
控制台日志(resp);
});
});
函数getImages(id){
风险值数据={
“操作”:“获取图像”,
“id”:id,
};
返回$.post(ajaxurl,数据)
}
第1项
第2项
第3项
第4项
第5项