得到的javascript表单数据,然后提交到PHP文件中使用AJAX表单、文件、数据、javascript

2023-09-11 01:34:53 作者:演不完的人间戏一场ゞ

我有一些麻烦的工作了如何将数据从一个表来发表通过AJAX。我有以下的code,但它似乎并没有从像复选框和单选按钮元素,虽然发送的数据。相反,它正在发送,虽然所有字段。也就是说,如果有一组单选按钮它是通过所有的可能性不只是检查那些发送。该表格​​可以由任何类型的元素,并在其元素的破坏量,所以我需要遍历我的方式。这部分似乎是工作,但我似乎无法得到的JavaScript抢选定的数据。我是否需要手动检查每个元素的类型,然后检查,看它是否检查等?

I am having some trouble working out how to get data from a form to post via ajax. I have the following code but it doesn't seem to be sending though the data from elements like checkboxes and radio buttons. Instead it is sending though all the fields. ie if there is a set of radiobuttons it is sending through all the possibilities not just the checked ones. The form can be made up of any type of element and have an undermined amount of elements in it, so I need to iterate through in the way I am. That part seems to be working, but I can't seem to get the javascript to grab the selected data. Do I need to manually check each element's type and then check to see if it checked etc?

myString = "";
my_form_id = "1";
my_url = "phpscript.php";
elem = document.getElementById("form_" + my_form_id).elements;
for(var i = 0; i < elem.length; i++)
{
     if (i>0) { myString += "&"; }
     myString += elem[i].name + "=" + elem[i].value;
}  
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});

`

推荐答案

由于您使用jQuery,您可以大大简化了一切:

Since you're using jQuery, you can drastically simplify it all:

var my_form_id = "1";
var my_url = "phpscript.php";
var form = $("#form_" + my_form_id);

$.ajax({
    type: "POST",
    url: my_url,
    data: form.serialize(),
    success: function(data) {
        // process the post data
    }
});

jQuery的序列的方法做所有的工作适合你。但是,如果你想手工做的,那么,你就必须检查每个字段。

jQuery's serialize method does all the work for you. But if you wanted to do it by hand, then yes, you would have to check each field.