何时在 ajax 调用中使用 JSON.stringify()

Jac*_*alo 3 javascript ajax jquery json

我对 ajax 和 JSON 的了解有限,但我知道在 ajax 调用中使用 JSON.stringify 有时会很有用。我下面的 ajax 调用工作正常,而下面的 stringify 方法则不起作用。我想知道我是否正确使用 .stringify,如果没有,我什么时候应该在 ajax 中使用 JSON.stringify(如果有的话)。我将 MVS 与模型、视图和控制器一起使用。

这就是我通常进行 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
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

下面我尝试使用 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
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

其附带的控制器方法接受 id 作为 int,而其他所有内容都是字符串。我之前曾使用过 JSON.stringify 和混合变量(整数、布尔值、字符串),没有出现任何问题。

任何有用的信息将不胜感激,

谢谢!

Win*_*ier 5

这是两个不同的字符串(它们最终评估的值)。一个不等于另一个。Stringify 不会按照您的要求产生“=”。

阅读这篇文章以在 get 调用中传递数据

JSON.stringify({
                "id": id,
                "name": name,
                "type": type,
                "description": description,
                "email": email
            }),

url: '@Url.Action("AddEquipment", "Home")' + '/?id=' + id +
                "&name=" + name + "&type=" + type + "&description=" +
                description + "&email=" + email 
Run Code Online (Sandbox Code Playgroud)