jQuery的ajax調用很方便,傳參的時候喜歡用Json的數據格式。比如:
復制代碼 代碼如下:
function AddComment(content) {
var threadId = $("#span_thread_id").html();
var groupId = $("#span_group_id").html();
var groupType = $("#span_group_type").html();
var title = $("#thread_title").html();
var content = content.replace(/\x22/g,'"');
$.ajax({
url: '/WebService/GroupService.asmx/AddThreadComment',
data: '{threadId:' + threadId + ',groupId:' + groupId + ',groupType:' + groupType + ',title:"' + title + '",content:"' + content + '"}', type: 'post',
dataType: 'json',
contentType: 'application/json;charset=utf-8',
cache: false,
success: function(data) {
//根據返回值data.d判斷是不是成功
},
error: function(xhr) {
//中間發生異常,查看xhr.responseText
}
});
}
這中間最麻煩,最容易出錯的也是拼接Json字符串,字符型參數的值要添加引號,而且對于用戶輸入的文本字段要對',/等進行特殊處理
意外的機會,上司給我推薦了一種新的方法,看下面代碼:
復制代碼 代碼如下:
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),
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插件:http://code.google.com/p/jquery-json/
您可能感興趣的文章:- html+js+php一次原始的Ajax請求示例
- jquery教程ajax請求json數據示例
- 使用$.getJSON實現跨域ajax請求示例代碼
- jQuery中使用Ajax獲取JSON格式數據示例代碼
- jquery ajax對特殊字符進行轉義防止js注入使用示例
- 通過AJAX的JS、JQuery兩種方式解析XML示例介紹
- ajax后臺處理返回json值示例代碼
- AJAX如何接收JSON數據示例介紹
- 淺析ajax請求json數據并用js解析(示例分析)
- JavaScript中的ajax功能的概念和示例詳解