简体   繁体   English

jQuery $ .when()和Ajax调用

[英]jQuery $.when() and ajax call

I'm a little confusing of how I can wait ajax return values and then do something. 我对如何等待ajax返回值然后执行某些操作感到困惑。 Here what I tryed: 这是我尝试的:

$('.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();
}

But console.log(resp.responseJSON); 但是console.log(resp.responseJSON); immediattely return undefined; 立即返回undefined;

The ajax call was tested before and is returning results. Ajax调用之前已经过测试,并且正在返回结果。

You don't need the $.when or the $.Deferred() since jQuery ajax methods already return a deferred/promise object. 你并不需要$.when$.Deferred()因为jQuery的AJAX方法已经返回递延/承诺对象。

 var ajaxurl ='https://my-json-server.typicode.com/typicode/demo/posts' $('.project-item').on('click', function(){ var id = $(this).attr('id'); getImages(id).done(function(resp) { console.clear(); console.log(resp); }); }); function getImages(id) { var data = { 'action' : 'getImages', 'id' : id, }; return $.post(ajaxurl, data) } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li class="project-item" id="10">Item 1</li> <li class="project-item" id="20">Item 2</li> <li class="project-item" id="30">Item 3</li> <li class="project-item" id="40">Item 4</li> <li class="project-item" id="50">Item 5</li> </ul> 

You can do this with plain old JavaScript 您可以使用普通的旧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)
});

See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 参见https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM