简体   繁体   中英

jQuery $.when() and ajax call

I'm a little confusing of how I can wait ajax return values and then do something. 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); immediattely return undefined;

The ajax call was tested before and is returning results.

You don't need the $.when or the $.Deferred() since jQuery ajax methods already return a deferred/promise object.

 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

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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