简体   繁体   中英

JavaScript - Building JSON object

I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:

$.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");
  }
});        

This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:

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");
  }
}); 

Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.

Thank you

You may want to look at the JSON JavaScript library . It has a stringify() function which I think will do exactly what you need.

Your code:

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

Take out the quotes ( line 3 ):

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

Remove the quotes

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

becomes

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

JSONs are objects not strings.

这应该工作

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

this works for me.

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

italics are the variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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