用 jQuery 的 Ajax 調用後台時,習慣以 JSON 格式傳參。手工拼接 JSON 字符串既繁瑣又容易出錯(字符串值要加引號、用戶輸入還需對引號等特殊字符轉義)。
function AddComment(content) {
var threadId = $("#span_thread_id").html();
var groupId = $("#span_group_id").html();
var content = content.replace(/\x22/g, '"');
$.ajax({
url: '/WebService/GroupService.asmx/AddThreadComment',
data: '{threadId:' + threadId + ',groupId:' + groupId
+ ',content:"' + content + '"}',
type: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
cache: false,
success: function(data) { /* 根據 data.d 判斷是否成功 */ },
error: function(xhr) { /* 查看 xhr.responseText */ }
});
}
function AddComment(content) {
var comment = {};
comment.threadId = $("#span_thread_id").html();
comment.groupId = $("#span_group_id").html();
comment.groupType = $("#span_group_type").html();
comment.title = $("#thread_title").html();
comment.content = content;
$.ajax({
url: '/WebService/GroupService.asmx/AddThreadComment',
data: $.toJSON(comment), // 直接把對象序列化為 JSON
type: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
cache: false,
success: function(data) { /* 根據 data.d 處理 */ },
error: function(xhr) { /* 查看 xhr.responseText */ }
});
}
相比手工拼接,方式二先構造普通對象、再用 $.toJSON(對象) 序列化,既省去引號與轉義的煩惱,也更不易出錯。該方法來自 jQuery 的 JSON 插件。