jQuery的ajax传参巧用JSON使用示例(附Json插件)

发布时间:2022-04-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了jQuery的ajax传参巧用JSON使用示例(附Json插件)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
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/

脚本宝典总结

以上是脚本宝典为你收集整理的jQuery的ajax传参巧用JSON使用示例(附Json插件)全部内容,希望文章能够帮你解决jQuery的ajax传参巧用JSON使用示例(附Json插件)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。