// Initialize the object, before adding data to it.
var NewPerson = new Object();
NewPerson.FirstName = $("#FirstName").val();
NewPerson.LastName = $("#LastName").val();
NewPerson.Address = $("#Address").val();
NewPerson.City = $("#City").val();
NewPerson.State = $("#State").val();
NewPerson.Zip = $("#Zip").val();
In actual I'm populating and sending an array of NewPerson objects. I'm using all the properties in my javascript but when I make ajax call like below, I want to only send two of the properties say for FirstName
and LastName
$.ajax({
type: "POST",
contentType开发者_StackOverflow中文版: "application/json; charset=utf-8",
url: "PersonService.asmx/AddPerson",
data: "{'NewPerson':" + JSON.stringify(NewPerson) + "}",
dataType: "json"
});
NOTE: I'm using an array not a single object of NewPerson
. The above code is just for example.
You can easily write a function to achieve that:
function extractMembers(arr, members)
{
var m, o, i, j;
var output = [];
for (i = 0; i < arr.length; ++i) {
o = {};
for (j = 0; j < members.length; ++j) {
m = members[j];
o[m] = arr[i][m];
}
output.push(o);
}
return output;
}
Now you can use the function like this:
var objects = [{FirstName: "...", LastName: "...", Address: "..."},
{FirstName: "...", LastName: "...", Address: "..."}]
var toSend = extractMembers(objects, ["FirstName", "LastName"]);
One more thing: You might want to use the short-notation to create objects in JavaScript:
var NewPerson = {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
...
};
Unfortunatly, you can't tell JSON.stringify
which propertys of an object/array you want to parse and which not. If you really need to create the NewPerson
object "manually", you have to filter the values which you want to send yourself.
A better approach seems to be the method .serialize()
or .serializeArray()
. Both will read
input
elements from a form
element, but only those, which own a name=
property. So you could just give #FirstName and #LastName a name property.
Reference: .serializeArray(), .serialize()
精彩评论