[英]Send only few properties of objects within an Array in ajax call with jQuery
// 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. 实际上,我正在填充并发送一个NewPerson对象数组。 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
我正在使用JavaScript中的所有属性,但是当我进行如下所示的ajax调用时,我只想发送两个属性,例如说
FirstName
和LastName
$.ajax({
type: "POST",
contentType: "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
. 注意:我使用的数组不是
NewPerson
的单个对象。 The above code is just for example. 上面的代码仅作为示例。
Unfortunatly, you can't tell JSON.stringify
which propertys of an object/array you want to parse and which not. 不幸的是,您无法告诉
JSON.stringify
您要解析的对象/数组的哪些属性,而哪些不是。 If you really need to create the NewPerson
object "manually", you have to filter the values which you want to send yourself. 如果确实需要“手动”创建
NewPerson
对象,则必须过滤要发送给自己的值。
A better approach seems to be the method .serialize()
or .serializeArray()
. 更好的方法似乎是方法
.serialize()
或.serializeArray()
。 Both will read input
elements from a form
element, but only those, which own a name=
property. 两者都将从
form
元素中读取input
元素,但仅读取那些拥有name=
属性的元素。 So you could just give #FirstName and #LastName a name property. 因此,您可以给#FirstName和#LastName一个name属性。
Reference: .serializeArray() , .serialize() 参考: .serializeArray() ,.serialize()
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: 还有一件事:您可能想使用简写形式在JavaScript中创建对象:
var NewPerson = {
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.