DIV CSS 佈局教程網

jQuery Ajax 傳參巧用 JSON——附 JSON 插件用法
編輯:AJAX基礎知識     

用 jQuery 的 Ajax 調用後台時,習慣以 JSON 格式傳參。手工拼接 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 */ }
    });
}

方式二:用 $.toJSON(對象) 自動序列化(推薦)

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 插件。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved