My knowledge of ajax and JSON is limited, but I know that using JSON.stringify in an ajax call can sometimes be useful. I have an ajax call below that works fine, while the one below it with the stringify method that does not work. I am wondering if I am using .stringify correctly, and if not, when should I use JSON.stringify in ajax, if ever. I am using MVS with a model, view, and controller.
This is how I usually do ajax calls, and how i build the url portion.
function AddEquipment(id, name, type, description, email) {
$.ajax({
url: '@Url.Action("AddEquipment", "Home")' + '/?id=' + id +
"&name=" + name + "&type=" + type + "&description=" +
description + "&email=" + email,
type: "GET",
cache: false,
datatype: "JSON",
success: function(result) {
//do stuff
}
});
}
Below I have tried using JSON.stringify instead of building the entire url manually, and it does not work.
function AddEquipment(id, name, type, description, email) {
$.ajax({
url: '@Url.Action("AddEquipment", "Home")',
type: "GET",
cache: false,
datatype: "JSON",
data: JSON.stringify({
"id": id,
"name": name,
"type": type,
"description": description,
"email": email
}),
success: function(result) {
//do stuff
}
});
}
the controller method this goes with accepts id as an int, while everything else is a string. I have used JSON.stringify before with mixed variables (ints, bools, strings) without an issue.
Any helpful information is greatly appreciated,
Thanks!
JSON.stringifyat all. If you passdataas an object, jQuery will convert to a query string properly. If you pass a string, such as JSON, then it is expected that the string is already in the properkey=value&k2=v2...format, not a JSON string.