我的ajax和JSON知识有限,但我知道在ajax调用中使用JSON.stringify有时是有用的。我下面有一个正常工作的ajax调用,而下面的带有stringify方法的调用却无法工作。我想知道我是否正确使用了stringify,如果没有,那么什么时候应该在ajax中使用JSON.stringify呢?我正在使用带有模型、视图和控制器的MVS。
这是我通常进行ajax调用的方式,并且如何构建url部分。
这是我通常进行ajax调用的方式,并且如何构建url部分。
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
}
});
}
我尝试使用JSON.stringify代替手动构建整个URL,但它不起作用。
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
}
});
}
这个控制器方法接受一个整数类型的id,而其他所有内容都是字符串。我之前已经使用了JSON.stringify处理混合变量(整数、布尔和字符串),没有遇到问题。
非常感谢提供任何有用的信息。
谢谢!
JSON.stringify
。如果将data
作为对象传递,则 jQuery 将正确地将其转换为查询字符串。如果传递字符串(例如 JSON),则预期该字符串已经处于正确的key=value&k2=v2...
格式,而不是一个 JSON 字符串。 - Jonathan Kuhn