Sending all input fields with jquery .post()
I have collected the values of all input field into an array as follows:开发者_开发知识库
$( ".formbox" ) . each( function(id,elem){
form_fields[ "input-" + $( elem ) . attr( "id" ) ] = $( elem ) . val( );
});
$.log( "Collected:", form_fields );
This does work, and then I try passing the array using post
$.post(
"server.php",
{
fields: form_fields
},
function(ret) {
if (!ret.success )
alert ( "Error! Reload please!" );
else
{
}
},
'json'
);
However while retrieving, Firebug indicates that the fields are empty
As I understood I need to serialize the array or not use it at all. But what could I use instead?
Please tell what is it that I am doing wrong?
---------- added ---------- ...I just found this
form_fields = {};
:)
I don't understand how but that solved the problem Please tell me what the difference is between an Array and {}? What does {} in JS ?
{}
is used for creating objects and []
is used for arrays to indicate indexes. The difference is that.
Sample code:
var obj = {name:"Captain",last_name:"Caveman",run:function(speed){//run;}}
//equivalent to
var obj = new Object();
obj.name = "Captain";
obj.last_name = "caveman";
obj.run = function(speed){
//run;
}
I've just created a new object on-the-fly with {}
follow the code below to call its members
document.write(obj.name);
document.write(obj.run("fast"));
But arrays are more simple than an object.
JSON: Javascript Object Notation
More about JSON: http://www.w3schools.com/js/js_objects.asp
More about Arrays: http://www.w3schools.com/js/js_obj_array.asp
I can only recommend the JQuery form plugin. It takes care of all this mess and even supports a transparent file upload mode. (Because normally you cant upload files using AJAX.)
Try:
var fields = {};
$('.formbox input').each(function(){
var $this = $(this);
fields['input-' + $this.attr('name')] = $this.val();
});
$.log( "Collected:", fields );
$.post("server.php", fields, function(ret) {
if (!ret.success)
alert ( "Error! Reload please!" );
else{
}
}, 'json');
form_fields = {};
means assign an empty Object to form_fields
. {}
is used to denote objects, whereas []
is used to denote arrays.
精彩评论