用ajax发送表单数据表单、数据、ajax

2023-09-10 16:15:04 作者:活着就是要没心没肺~

我要发送的所有输入与阿贾克斯。我的表单有一个表格是这样的。

I want to send all input in a form with ajax .I have a form like this.

<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>

而在.js文件中,我们有以下code:

And in .js file we have following code :

function f (form ,fname ,lname ){
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;

但这不是working.i不想使用表格的内容

But this is not working.i don't want to use Form data .

推荐答案

据我们希望把所有具有name属性的表单输入字段,你可以做到这一点对所有形式的,无论字段名:

as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:

首个解决方案

function submitForm(form){
    var url = form.attr("action");
    var formData = {};
    $(form).find("input[name]").each(function (index, node) {
        formData[node.name] = node.value;
    });
    $.post(url, formData).done(function (data) {
        alert(data);
    });
}

第二个解决方案:在这个解决方案,您可以创建输入值的数组:

Second Solution: in this solution you can create an array of input values:

function submitForm(form){
    var url = form.attr("action");
    var formData = $(form).serializeArray();
    $.post(url, formData).done(function (data) {
        alert(data);
    });
}