欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-10-30 23:38:00
jquery的ajax调用很方便,传参的时候喜欢用json的数据格式。比如: 复制代码 代码如下: function addcomment(content) { var t...
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/