jQuery的ajax传参巧用JSON使用过程是怎样的

发布时间:2021-10-08 13:57:08 作者:柒染
来源:亿速云 阅读:103

这期内容当中小编将会给大家带来有关jQuery的ajax传参巧用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使用过程是怎样的了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. django控件及传参的使用案例
  2. jquery如何传参及获取

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jquery ajax json

上一篇:如何实现ASP.Net中表单POST到其他页面

下一篇:如何实现shell脚本监控linux系统内存使用情况

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》