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

时间:2015-02-27 16:13:12

标签: javascript php jquery ajax

我想首先追加,然后运行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); 
							});
  });

2 个答案:

答案 0 :(得分:2)

$ .post()函数返回一个promise。您可以在此承诺上调用done()函数。 done()函数接受一个回调函数,该函数将在完成对服务器的发布后执行:

$.post("update.inc.php", {
      tag : $(this).closest("a").text(),
      users_id : $("#users_id").val()
    }).done(function(){

      // your second post goes here

    });

答案 1 :(得分:1)

您可以使用$.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

中提供了更多详细信息