通过ajax传递post变量

我有一个链接:

 

它会触发ajax调用

 $(".tag").click(function() { var for_user_id = $(this).attr("for_user_id"); var wl_id = $(this).attr("wl_id"); var wi_id = $(this).attr("wi_id"); $.ajax({ type: "POST", url: "/ajax/actions/tag.php", data: { 'for_user_id': 'for_user_id', 'wl_id': 'wl_id', 'wi_id': 'wi_id' }, success: function(data){ $(this).text("You've tagged this"); $(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged'); $(this).closest('.gl_buttons').addClass('tagged'); } }); return false; }); 

但在控制台中我看到以下内容:

 TypeError: e is undefined 

ajax文件被处理但POST数据为空,并且不会发生成功操作,因此它会以零发布,并且类不会更改

我盯着看着……什么明显的?

this不会自动传递给AJAX回调函数。 您可以使用context:参数告诉jQuery传递它:

  $.ajax({ type: "POST", url: "/ajax/actions/tag.php", data: { 'for_user_id': for_user_id, 'wl_id': wl_id, 'wi_id': wi_id }, context: this, success: function(data){ $(this).text("You've tagged this"); $(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged'); $(this).closest('.gl_buttons').addClass('tagged'); } }); 

您发送的数据错误,请勿在单引号内调用您的变量。

 $(".tag").click(function() { var for_user_id = $(this).attr("for_user_id"); var wl_id = $(this).attr("wl_id"); var wi_id = $(this).attr("wi_id"); $.ajax({ type: "POST", url: "/ajax/actions/tag.php", data: { 'for_user_id': for_user_id, 'wl_id': wl_id, 'wi_id': wi_id }, success: function(data){ $(this).text("You've tagged this"); $(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged'); $(this).closest('.gl_buttons').addClass('tagged'); } }); return false; });