aja传出json

本文介绍了一种简化jQuery调用JSON数据的方法,通过使用对象直接赋值来构造JSON数据字符串,避免了手动拼接字符串的繁琐过程,提高了代码的可读性和减少错误率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有些时候jquery调用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数据串的时候很麻烦,容易出错。用下面的方法处理构造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 
        } 
    }); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值