主页 > 知识库 > jQuery的ajax传参巧用JSON使用示例(附Json插件)

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

热门标签:团购网站 电子围栏 服务器配置 阿里云 银行业务 科大讯飞语音识别系统 Mysql连接数设置 Linux服务器
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/
您可能感兴趣的文章:
  • html+js+php一次原始的Ajax请求示例
  • jquery教程ajax请求json数据示例
  • 使用$.getJSON实现跨域ajax请求示例代码
  • jQuery中使用Ajax获取JSON格式数据示例代码
  • jquery ajax对特殊字符进行转义防止js注入使用示例
  • 通过AJAX的JS、JQuery两种方式解析XML示例介绍
  • ajax后台处理返回json值示例代码
  • AJAX如何接收JSON数据示例介绍
  • 浅析ajax请求json数据并用js解析(示例分析)
  • JavaScript中的ajax功能的概念和示例详解

标签:萍乡 广元 衢州 枣庄 大理 衡水 江苏 蚌埠

巨人网络通讯声明:本文标题《jQuery的ajax传参巧用JSON使用示例(附Json插件)》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266