jQuery的ajax傳參巧用JSON使用樣本(附Json外掛程式)_AJAX相關

來源:互聯網
上載者:User
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/
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.