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

所属分类: 网络编程 / AJAX相关 阅读数: 1358
收藏 0 赞 0 分享
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/
更多精彩内容其他人还在看

Baidu Musicbox 用到的ajax代码

Baidu Musicbox 用到的ajax代码
收藏 0 赞 0 分享

[asp]天枫AJAX百度音乐即时听附下载

[asp]天枫AJAX百度音乐即时听附下载
收藏 0 赞 0 分享

[asp]天枫AJAX blog V1.0 程序提供下载了

[asp]天枫AJAX blog V1.0 程序提供下载了
收藏 0 赞 0 分享

如何解决远程页面抓取中的乱码问题

如何解决远程页面抓取中的乱码问题
收藏 0 赞 0 分享

一个方便AJAX开发的通用类

一个方便AJAX开发的通用类
收藏 0 赞 0 分享

AJAXRequest v0.2

AJAXRequest v0.2
收藏 0 赞 0 分享

一个简单的AJAX请求类

一个简单的AJAX请求类
收藏 0 赞 0 分享

一个Ajax类

一个Ajax类
收藏 0 赞 0 分享

AJAX 常用函数

AJAX 常用函数
收藏 0 赞 0 分享

[ASP.NET Ajax] ECMAScript基础类以及Asp.net Ajax对类<Object>的扩展

[ASP.NET Ajax] ECMAScript基础类以及Asp.net Ajax对类<Object>的扩展
收藏 0 赞 0 分享
查看更多