【问题标题】:When to use JSON.stringify() in an ajax call [duplicate]何时在 ajax 调用中使用 JSON.stringify() [重复]
【发布时间】:2016-11-21 22:04:08
【问题描述】:

我对 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
            }
        });
    }

下面我尝试使用 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 作为 int,而其他所有内容都是字符串。我之前使用 JSON.stringify 和混合变量(整数、布尔值、字符串)没有问题。

非常感谢任何有用的信息,

谢谢!

【问题讨论】:

  • 我相信 jQuery 为您完成了繁重的工作......只需将数据作为对象传递 - 阅读 documentation 了解更多信息
  • 您是否打开了开发人员工具并查看了“网络”选项卡以查看 AJAX 调用的 URL 与此 JSON 代码的实际结果是什么?
  • JSON 通常会通过 POST 方法发送,然后请求正文将包含数据。如果您想通过查询参数发送,您可能需要字符串化,然后在其上使用 encodeURIComponent。然后你可以在服务器端做相反的事情。
  • 在这种情况下,根本不要使用JSON.stringify。如果您将data 作为对象传递,jQuery 将正确转换为查询字符串。如果您传递一个字符串,例如 JSON,那么该字符串应该已经是正确的key=value&k2=v2... 格式,而不是 JSON 字符串。

标签: javascript jquery json ajax


【解决方案1】:

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

阅读此post 以在 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 

【讨论】:

  • 其实它们根本就不是对象。
  • @Bergi 是的,而是字符串! :) 我说的是 url(不管它最终是什么)和 JSON.stringify
  • 如果您发现一个问题与当前问题相同,您可以点击该问题下方的标记链接并将其标记为重复。
猜你喜欢
  • 2021-05-20
  • 2013-07-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 2015-07-04
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多