JavaScript - 构建JSON对象

use*_*662 9 javascript jquery json

我试图了解如何在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");
  }
});        
Run Code Online (Sandbox Code Playgroud)

这种方法有效.但是,我需要动态构建我的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");
  }
}); 
Run Code Online (Sandbox Code Playgroud)

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

谢谢

LBu*_*kin 8

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


Sha*_*ggy 6

你的代码:

var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
Run Code Online (Sandbox Code Playgroud)

取出引号(第3行):

var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };
Run Code Online (Sandbox Code Playgroud)