繁体   English   中英

JavaScript - 构建JSON对象

[英]JavaScript - Building JSON object

我试图了解如何在JavaScript中构建JSON对象。 这个JSON对象将被传递给JQuery ajax调用。 目前,我正在硬编码我的JSON并进行如下所示的JQuery调用:

$.ajax({
  url: "/services/myService.svc/PostComment",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: '{"comments":"test","priority":"1"}',
  dataType: "json",
  success: function (res) {
    alert("Thank you!");
  },
  error: function (req, msg, obj) {
    alert("There was an error");
  }
});        

这种方法有效。 但是,我需要动态构建我的JSON并将其传递给JQuery调用。 但是,我无法弄清楚如何动态构建JSON对象。 目前,我正在尝试以下运气:

var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };

$.ajax({
  url: "/services/myService.svc/PostComment",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: json,
  dataType: "json",
  success: function (res) {
    alert("Thank you!");
  },
  error: function (req, msg, obj) {
    alert("There was an error");
  }
}); 

有人可以告诉我我做错了什么吗? 我注意到,在第二个版本中,我的服务甚至没有达到。

谢谢

您可能想要查看JSON JavaScript库 它有一个stringify()函数,我认为它将完全符合您的需要。

你的代码:

var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };

取出引号(第3行):

var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };

删除引号

data: '{"comments":"test","priority":"1"}',

data: {"comments":"test","priority":"1"},

JSON是对象而不是字符串。

这应该工作

var json = { comments: "comments",priority: "priority" };

这对我有用。

var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";

斜体是变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM