[英]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.