简体   繁体   中英

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. 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: "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.

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()

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(),
    ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM