如何先追加,然后在jquery中运行ajax


How to append first, then run ajax in jquery?

我想先追加,然后运行ajax更新数据,然后进行搜索。请参阅下面的代码。我想放一个类似if append的代码,然后运行$.post。我如何在jquery中做到这一点,谢谢?

$('<span />', { class: 'result_tag', text: href }).insertBefore($input);
		       
 $('.result_tag').append(' ');
//make sure append first and then run .post
$.post("member_search.php", {
	search_text: $(".result_tag").text()
     }).done(function()
{							
$.post("member_search.php", {
	      search_text: $(".result_tag").text()
},
		function(data){
	$("#find_members").html(data); 
							});
  });

$.post()函数返回一个promise。您可以调用此promise的done()函数。done()函数接受一个回调函数,该函数将在发送到服务器后执行:

$.post("update.inc.php", {
      tag : $(this).closest("a").text(),
      users_id : $("#users_id").val()
    }).done(function(){
      // your second post goes here
    });

您可以像这样使用$.ajax及其事件beforeSend

$.ajax({
  url: "http://fiddle.jshell.net/favicon.png",
  data: 'search_text='+$(".result_tag").text(),
  beforeSend: function( xhr ) {
    $('.result_tag').append(' ');
  }
})
  .done(function( data ) {
    //now do your other ajax things
  });

希望这对你有帮助。

更多详细信息请参阅jQuery DOC