I have following jQuery code and it works fine and I am able to deserialize it in the server properly.
But when I tried to create a variable and pass that as a JSON obje
Your two examples do not pass the same data
argument to $.getJSON()
.
The working example passes this object:
{
Accrual: "A",
Brand: "B"
}
The non-working example passes this object:
{
searchCriteria: {
Accrual: "A",
Brand: "B"
}
}
See the difference?
To fix the non-working example, where you pass { searchCriteria: searchCriteria }
into $.getJSON()
, you can change it to searchCriteria
, thus removing the extra level of object.
Also note that these are JavaScript objects you're working with here, not JSON. For example, you don't have to quote the property names like "Accrual"
as required by JSON. (It doesn't hurt anything to quote the property names, it just isn't necessary in a JavaScript object.) It's useful to know when you are dealing specifically with JSON and when you are dealing with ordinary JavaScript objects, because they're not the same thing.
Your commented code passes a different object to the non-commented code
Commented data (non-working):
{
searchCriteria: {
Accrual: "A",
Brand: "B"
}
}
Uncommented data (working):
{
Accrual: "A",
Brand: "B"
}
the original commented ajax request should be:
$.getJSON(url, searchCriteria, function (data) {
if (data.length) {
alert('Success');
}
});