开发者

get form data with javascript and then submit it to a php file using ajax

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 + "=" + e开发者_JAVA百科lem[i].value;
}  
$.ajax({
type: "POST",
url: my_url,
data: myString,
success: function(data) {
// process the post data
}
});

`


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'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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜