DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX基礎知識 >> jQuery的ajax傳參巧用JSON使用示例(附Json插件)
jQuery的ajax傳參巧用JSON使用示例(附Json插件)
編輯:AJAX基礎知識     
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/
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved