如何使用AJAX提交表单?

时间:2022-11-23 16:46:04

I have an event listener:

我有一个事件监听器:

$('button.publish').live('click', function() {
    //enter code here
});

This button element is inside a form. I know that I can't use $(this).submit(); 'cause it will cause refresh. I also can't target the form by its ID because I'm trying to make it for general use (add news, add contact, add ...).

此按钮元素位于表单内。我知道我不能使用$(this).submit();因为它会导致刷新。我也无法通过其ID来定位表单,因为我正在尝试将其用于一般用途(添加新闻,添加联系人,添加...)。

Knowing this, I can use the form's action for this is different from each other but I don't know how to submit the form inside the button event listener using AJAX (using $.post()).

知道了这一点,我可以使用表单的动作,因为它彼此不同,但我不知道如何使用AJAX(使用$ .post())在按钮事件监听器中提交表单。

Is this the correct use:

这是正确的用法:

var form = $(this).closest('form');
$.post(form.attr('action'), form.serializeArray(), callback, type);

Or there is a better way?

还是有更好的方法?

2 个解决方案

#1


0  

What you have is correct, you can use .serliaze() to save a few steps on the jQuery side, like this:

你有什么是正确的,你可以使用.serliaze()在jQuery端保存一些步骤,如下所示:

var form = $(this).closest('form');
$.post(form.attr('action'), form.serialize(), function(data) {
  alert("The response was: " + data);
});

#2


0  

I don't know an advanced way, but a simple way is to get each form element's data like with $("#bar").val(); quick example:

我不知道一种先进的方法,但一种简单的方法是获取每个表单元素的数据,如$(“#bar”)。val();快速示例:

$.ajax({
   type: "POST",
   url: "some.php",
   data: data: "bar="+$("#bar").val()+"&foo=bar",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

#1


0  

What you have is correct, you can use .serliaze() to save a few steps on the jQuery side, like this:

你有什么是正确的,你可以使用.serliaze()在jQuery端保存一些步骤,如下所示:

var form = $(this).closest('form');
$.post(form.attr('action'), form.serialize(), function(data) {
  alert("The response was: " + data);
});

#2


0  

I don't know an advanced way, but a simple way is to get each form element's data like with $("#bar").val(); quick example:

我不知道一种先进的方法,但一种简单的方法是获取每个表单元素的数据,如$(“#bar”)。val();快速示例:

$.ajax({
   type: "POST",
   url: "some.php",
   data: data: "bar="+$("#bar").val()+"&foo=bar",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });