jquery处理json数组 返回 怎么处理

24989人阅读
&!DOCTYPE html PUBLIC &-//W3C//DTD XHTML 1.0 Transitional//EN& &http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&&
&html xmlns=&http://www.w3.org/1999/xhtml&&
&title&&/title&
&script src=&JS/jquery-1.8.0.min.js& type=&text/javascript&&&/script&
&script type=&text/javascript&&
$(function () {
url: 'jsondata.ashx',
type: 'GET',
dataType: 'json',
timeout: 1000,
cache: false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction,
//错误执行方法
success: succFunction //成功执行方法
function LoadFunction() {
$(&#list&).html('加载中...');
function erryFunction() {
alert(&error&);
function succFunction(tt) {
$(&#list&).html('');
//eval将字符串转成对象数组
//var json = { &id&: &10086&, &uname&: &zhangsan&, &email&: && };
//json = eval(json);
//alert(&===json:id=& + json.id + &,uname=& + json.uname + &,email=& + json.email);
var json = eval(tt); //数组
$.each(json, function (index, item) {
//循环获取数据
var name = json[index].N
var idnumber = json[index].IdN
var sex = json[index].S
$(&#list&).html($(&#list&).html() + &&br&& + name + & - & + idnumber + & - & + sex + &&br/&&);
&ul id=&list&&
&%@ WebHandler Language=&C#& Class=&jsondata& %&
using System.W
using System.Web.Script.S
using System.IO;
using System.T
using System.Collections.G
using Newtonsoft.J
using System.D
public class jsondata : IHttpHandler {
public void ProcessRequest(HttpContext context)
context.Response.ContentType = &text/plain&;
string JsonStr = JsonConvert.SerializeObject(CreateDT());
context.Response.Write(JsonStr);
context.Response.End();
#region 创建测试数据源
//创建DataTable
protected DataTable CreateDT()
DataTable tblDatas = new DataTable(&Datas&);
//tblDatas.Columns.Add(&ID&, Type.GetType(&System.Int32&));
//tblDatas.Columns[0].AutoIncrement =
//tblDatas.Columns[0].AutoIncrementSeed = 1;
//tblDatas.Columns[0].AutoIncrementStep = 1;
tblDatas.Columns.Add(&IdNumber&, Type.GetType(&System.String&));
tblDatas.Columns.Add(&Name&, Type.GetType(&System.String&));
tblDatas.Columns.Add(&BirthDate&, Type.GetType(&System.String&));
tblDatas.Columns.Add(&Sex&, Type.GetType(&System.String&));
tblDatas.Columns.Add(&Wage&, Type.GetType(&System.Decimal&));
tblDatas.Columns.Add(&Bonus&, Type.GetType(&System.Decimal&));
//统计列开始
tblDatas.Columns.Add(&NeedPay&, Type.GetType(&System.String&), &Wage+Bonus&);
//统计列结束
tblDatas.Columns.Add(&Address&, Type.GetType(&System.String&));
tblDatas.Columns.Add(&PostCode&, Type.GetType(&System.String&));
//设置身份证号码为主键
tblDatas.PrimaryKey = new DataColumn[] { tblDatas.Columns[&IdNumber&] };
tblDatas.Rows.Add(new object[] { &00&, &张三&, &1982&, &0&, , null, &深圳市&, &518000& });
tblDatas.Rows.Add(new object[] { &01&, &李四&, &1983&, &1&, , null, &深圳市&, &518000& });
tblDatas.Rows.Add(new object[] { &02&, &王五&, &1984&, &1&, , null, &深圳市&, &518000& });
tblDatas.Rows.Add(new object[] { &03&, &赵六&, &1985&, &0&, , null, &深圳市&, &518000& });
tblDatas.Rows.Add(new object[] { &04&, &牛七&, &1986&, &1&, , null, &深圳市&, &518000& });
return tblD
#endregion
public bool IsReusable
&script type=&text/javascript&&
$(function () {
url: 'jsondata.ashx',
type: 'GET',
dataType: 'json',
timeout: 1000,
cache: false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction,
//错误执行方法
success: succFunction //成功执行方法
function LoadFunction() {
$(&#list&).html('加载中...');
function erryFunction() {
alert(&error&);
function succFunction(tt) {
$(&#list&).html('');
//eval将字符串转成对象数组
//var json = { &id&: &10086&, &uname&: &zhangsan&, &email&: && };
//json = eval(json);
//alert(&===json:id=& + json.id + &,uname=& + json.uname + &,email=& + json.email);
var json = eval(tt); //数组
$.each(json, function (index, item) {
//循环获取数据
var Key = json[index].
var Info = json[index].
var idnumber = json[index].IdN
var sex = json[index].S
$(&#list&).html($(&#list&).html() + &&br&& + Key + &----& + Info.name); //+ & - & + idnumber + & - & + sex + &&br/&&);
&%@ WebHandler Language=&C#& Class=&jsondata& %&
using System.W
using System.Web.Script.S
using System.IO;
using System.T
using System.C
using System.Collections.G
using System.D
public class jsondata : IHttpHandler {
public void ProcessRequest(HttpContext context)
context.Response.ContentType = &text/plain&;
context.Response.Cache.SetNoStore();
string data = &[{\&key\&:\&1\&,\&info\&:{\&name\&:\&222\&,\&age\&:\&333\&,\&sex\&:\&444\&}},{\&key\&:\&2\&,\&info\&:{\&name\&:\&999\&,\&age\&:\&000\&,\&sex\&:\&111\&}}]&;
context.Response.Write(new JavaScriptSerializer().Serialize(data));
public bool IsReusable
&%@ Page Language=&C#& AutoEventWireup=&true& CodeFile=&Test2013.aspx.cs& Inherits=&Test2013& %&
&!DOCTYPE html PUBLIC &-//W3C//DTD XHTML 1.0 Transitional//EN& &http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&&
&html xmlns=&http://www.w3.org/1999/xhtml&&
&head runat=&server&&
&title&&/title&
&script src=&JS/jquery-1.8.0.min.js& type=&text/javascript&&&/script&
&script type=&text/javascript&&
function GetPara(o) {
var sortid = $(o).val();
url: 'GetPara.ashx?type=get&sortid=' + sortid,
type: 'GET',
dataType: 'json',
timeout: 3000,
cache: false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction,
//错误执行方法
success: succFunction //成功执行方法
function LoadFunction() {
$(&#list&).html('加载中...');
function erryFunction() {
alert(&error&);
function succFunction(tt) {
$(&#list&).html('');
var json = eval(tt); //数组
$.each(json, function (index, item) {
//循环获取数据
var Id = json[index].
var Name = json[index].
$(&#list&).html($(&#list&).html() + &&br&& + Name + &&input type='text' id='& + Id + &' /&&br/&&);
function SavePara() {
var parameter = {};
$(&#list input:text&).each(function () {
var key = $(this).attr(&id&);
var value = $(this).val();
parameter[key] =
url: 'GetPara.ashx?type=save',
type: 'POST',
dataType: 'json',
data: parameter,
timeout: 3000,
cache: false,
beforeSend: LoadFunction, //加载执行方法
error: erryFunction,
//错误执行方法
success: succFunction //成功执行方法
function LoadFunction() {
function erryFunction() {
function succFunction(tt) {
&form id=&form1& runat=&server&&
&asp:DropDownList ID=&ddl1& runat=&server& onchange=&GetPara(this)&&
&/asp:DropDownList&
&ul id=&list&&&/ul&
&input type=&button& value=&保存数据& onclick=&SavePara()& /&
&%@ WebHandler Language=&C#& Class=&GetPara& %&
using System.W
using System.D
using System.Collections.G
using System.Web.Script.S
public class GetPara : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = &text/plain&;
string SortId = context.Request[&sortid&];
string Type = context.Request[&type&];
if (Type==&get&)
if (!string.IsNullOrEmpty(SortId))
DataTable dt = MSCL.SqlHelper.GetDataTable(&select * from PR_PRODUCTPARAS where sortid='& + SortId + &' &);
List&Paras& list = new List&Paras&();
for (int i = 0; i & dt.Rows.C i++)
Paras a = new Paras();
a.id = dt.Rows[i][&PARAID&].ToString();
a.name = dt.Rows[i][&PARANAME&].ToString();
list.Add(a);
context.Response.Write(new JavaScriptSerializer().Serialize(list));
else if (Type == &save&)
//反序列化json
System.IO.Stream stream = context.Request.InputS
System.IO.StreamReader sr = new System.IO.StreamReader(stream, System.Text.Encoding.GetEncoding(&UTF-8&));
string sJson = sr.ReadToEnd();
if (sJson.Contains(&&&))
string[] sArr = sJson.Split('&');
for (int i = 0; i & sArr.L i++)
string[] sArr1 = sArr[i].Split('=');
object id = sArr1[0];
object value = sArr1[1];
public bool IsReusable {
public struct Paras
版权声明:本文为博主原创文章,未经博主允许不得转载。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:471154次
积分:6763
积分:6763
排名:第1407名
原创:188篇
转载:156篇
评论:58条
(1)(1)(7)(12)(7)(3)(4)(6)(6)(5)(13)(6)(4)(9)(6)(14)(6)(17)(6)(6)(5)(5)(18)(6)(19)(9)(19)(18)(41)(16)(22)(27)当前位置 &
Javascript教程_有关jQuery.autocomplete处理返回的JSON当成字符串的解决办法教程
有关jQuery.autocomplete处理返回的JSON当成字符串的解决办法教程
在网上看到的,都试过失败的情况下,终于看到可以用 eval() 函数可以解决,写下了以下的语句,请高手们指点一下。
在后台返回一个JSON格式的字符串
C#[ReadData.aspx],以下是用Response.Write();的返回结果;
[{Sid:&1&,S_Title:&这是第一个JSON&,S_Count:&500&},{Sid:&3&,S_Title:&这是第二个JSON&,S_Count:&125&},{Sid:&3&,S_Title:&这是第三个JSON&,S_Count:&360&}]
如果要获取Sid,还要在最后设置 .result()。
var Index=-1;
$(&#txtTitle&).autocomplete(&ReadData.aspx&,{
& & matchContains: true,
& & matchCase:false,
& & selectFirst:false,
& & cacheLength:1,
& & delay:5,
& & extraParams:{status:&2&,limit:&10&},
& & parse:function(data){
& &&&//data=rs(data);    //这是如果不是返回JSON格式的字符串所要用的;
& &&&var d=eval(&(&+data+&)&);    //此处要用eval函数;
& &&&var rows=new Array();
& &&&for(var i=0;i&d.i++){
& && &rows[rows.length]={data:d[i],value:d[i].Sid,result:d[i].S_Title}
& & formatItem:function(row,i,max){
& &&&var Content = i+&/&+max+&: [&font color='red'&&+row.Sid+&&/font&] &+ row.S_T
& &&&if(null!=row.S_Count) Content += & [&font color=\&red\&&& + row.S_Count+&&/font&]&;
& & return C
& & formatMatch:function(row,i,max){
& &&&return row.S_T    //这个不知道为什么不能return row.Sid+& &+row.S_T
& & formatResult:function(row,i,max){
& &&&return row.S_T    //这个不知道为什么获取不了 row.S
}).result(function(event,data,formatted){
& &Index=((data!=null&&null!=data.Sid)?eval(data.Sid):-1);
以下是处理一个返回不是JSON格式的字符串(例如&这是第一个JSON 1\n这是第二个JSON 2\n这是第三个JSON 3&)的函数;
&&function rs(data){
& &this.Sid=new Array();
& &this.S_Title=new Array();
& &data=data.split(&\n&);
& &var json='[';
& &for(var i=0;i&data.i++){
& & var Num=data[i].lastIndexOf(& &);
& & this.S_Title[i]=data[i].substring(0,Num);
& & this.Sid[i]=data[i].substring(Num+1,data[i].length);
& & json+='{Sid:&'+this.Sid[i]+'&,S_Title:&'+this.S_Title[i]+'&}';
& & if(i&data.length-1) json+=',';
& &json+=']';
& &//json='[{Sid:& &,S_Title:& &},{Sid:& &,S_Title:& &},{Sid:& &,S_Title:& &}]';&&JSON的格式
以上代码只在IE上执行,没有在其他浏览器测试过。
视频教程列表
文章教程搜索
输入您的搜索字词
提交搜索表单
Javascript推荐教程
tel:<font color="#FF30058JQuery ajax返回JSON时的处理方式
最近在使用JQuery的ajax方法时,要求返回的数据为json数据,在处理的过程中遇到下面的几个问题,那就是采用不同的方式来生成json数据的时候,在$.ajax方法中应该是如何来处理的,下面依次来进行说明,由于本人使用的是asp.net,所以处理的页面都是采用.net来做的!其他的方式应该是相同的吧
&&&&&&&& 首先给出要传的json数据:[{&demoData&:&This Is The JSON Data&}]
&&&&&&& 1,使用普通的aspx页面来处理
&&&&&& 本人觉得这种方式处理起来是最简单的了,看下面的代码吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& type:& &post&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& url:& &Default.aspx&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& dataType:& &json&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& success:& function (data) {&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& $( &input#showTime&).val(data[0].demoData);&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& },&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& error:& function (XMLHttpRequest, textStatus, errorThrown) {&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& alert(errorThrown);&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& }&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& });
&&&&&&&& 这里是后台传递数据的代码
Response.Clear();&
&&&&&&&&&&&&&&&&&&&&&&& Response.Write( &[{\&demoData\&:\&This Is The JSON Data\&}]&);&
&&&&&&&&&&&&&&&&&&&&&&& Response.Flush();&
&&&&&&&&&&&&&&&&&&&&&&& Response.End();
&&&&&&&& 这种处理的方式将传递过来的数据直接解析为json数据,也就是说这里的前台js代码可能直接把这些数据解析成json对象数据,而并非字符串数据,如data[0].demoData,这里就直接使用了这个json对象数据
&&&&&&&&& 2,使用webservice(asmx)来处理
这种处理方式就不会将传递过来的数据当成是json对象数据,而是作为字符串来处理的,如下代码
$.ajax({&&&&&
type:& &post&,&&&&&
url:& &JqueryCSMethodForm.asmx/GetDemoData&,&&&&&
dataType:& &json&, /*这句可用可不用,没有影响*/&
contentType:& &application/ charset=utf-8&,&&&&&
success:& function (data) {&&&&&
$( &input#showTime&).val(eval(&#39;(&#39; + data.d + &#39;)&#39;)[0].demoData);&
//这里有两种对数据的转换方式,两处理方式的效果一样//$(&input#showTime&).val(eval(data.d)[0].demoData);&
error:& function (XMLHttpRequest, textStatus, errorThrown) {&&&&&
alert(errorThrown);&&&&&
&&&&&&&& 下面这里为asmx的方法代码
[WebMethod]&&&&&
&public& static& string GetDemoData() {&&&&&
&return& &[{\&demoData\&:\&This Is The JSON Data\&}]&;&&&&&
&&&&&&&& 这里的这种处理方式就把传递回来的json数据当成了字符串来处理的,所在就要对这个数据进行eval的处理,这样才能成为真正的json对象数据,
&&&&&&&&& 3,使用ashx文件来处理
这种方式和普通的x的页面处理是一样的所以这里就不多做解释了
作者:xiahuawuyu
您对本文章有什么意见或着疑问吗?请到您的关注和建议是我们前行的参考和动力&&
您的浏览器不支持嵌入式框架,或者当前配置为不显示嵌入式框架。汇聚2000万达人的兴趣社区下载即送20张免费照片冲印
扫码下载App
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
VIM发烧友-面向对象编程OOP-迷人的火狐插件
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(732)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_',
blogTitle:'jQuery ajax返回parsererror错误的解决方法',
blogAbstract:'使用jQuery ajax下载图片,却返回parsererror错误,Google了一下,找到了解决方法:在jQuery中ajax请求方法返回的时候,会去解析返回的值,企图将返回值解析为文本,例如responseXML,或者\nresponseText。如果请求的数据为二进制数据(例如图片),jQuery就会报parsererror的错。其实这也不算是jQuery的Bug,因为XMLHTTPRequest的API原本就是为了处理纯文本形式的数据,但纯文本数据本身也是二进制的,XMLHTTPRequest是可以请求二进制数据的。\n',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:4,
publishTime:0,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:true,
hostIntro:'VIM发烧友-面向对象编程OOP-迷人的火狐插件',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}jQuery ajax - post() 方法
jQuery ajax - post() 方法
请求 test.php 网页,忽略返回值:
$.post(&test.php&);
通过 AJAX POST 请求改变 div 元素的文本:
$(&input&).keyup(function(){
txt=$(&input&).val();
$.post(&demo_ajax_gethint.asp&,{suggest:txt},function(result){
$(&span&).html(result);
定义和用法
post() 方法通过 HTTP POST 请求从服务器载入数据。
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
必需。规定把请求发送到哪个 URL。
可选。映射或字符串值。规定连同请求发送到服务器的数据。
success(data, textStatus, jqXHR)
可选。请求成功时执行的回调函数。
可选。规定预期的服务器响应的数据类型。
默认执行智能判断(xml、json、script 或 html)。
该函数是简写的 Ajax 函数,等价于:
type: 'POST',
data: data,
success: success,
dataType: dataType
根据响应的不同的 MIME 类型,传递给 success 回调函数的返回数据也有所不同,这些数据可以是 XML 根元素、文本字符串、JavaScript 文件或者 JSON 对象。也可向 success 回调函数传递响应的文本状态。
对于 jQuery 1.5,也可以向 success 回调函数传递 (jQuery 1.4 中传递的是 XMLHttpRequest 对象)。
大部分实现会规定一个 success 函数:
$.post(&ajax/test.html&, function(data) {
$(&.result&).html(data);
本例读取被请求的 HTML 片段,并插入页面中。
通过 POST 读取的页面不被缓存,因此
中的 cache 和 ifModified 选项不会影响这些请求。
注释:由于浏览器安全方面的限制,大多数 "Ajax" 请求遵守同源策略;请求无法从不同的域、子域或协议成功地取回数据。
注释:如果由 jQuery.post() 发起的请求返回错误代码,那么不会有任何提示,除非脚本已调用了全局的 。或者对于 jQuery 1.5,jQuery.post() 返回的 jqXHR 对象的 .error() 方法也可以用于错误处理。
jqXHR 对象
对于 jQuery 1.5,所有 jQuery 的 AJAX 方法返回的是 XMLHTTPRequest 对象的超集。由 $.post() 返回的 jQuery XHR 对象或 &jqXHR,&实现了约定的接口,赋予其所有的属性、方法,以及约定的行为。出于对由
使用的回调函数名称便利性和一致性的考虑,它提供了 .error(), .success() 以及 .complete() 方法。这些方法使用请求终止时调用的函数参数,该函数接受与对应命名的 $.ajax() 回调函数相同的参数。
jQuery 1.5 中的约定接口同样允许 jQuery 的 Ajax 方法,包括 $.post(),来链接同一请求的多个 .success()、.complete() 以及 .error() 回调函数,甚至会在请求也许已经完成后分配这些回调函数。
// 请求生成后立即分配处理程序,请记住该请求针对 jqxhr 对象
var jqxhr = $.post(&example.php&, function() {
alert(&success&);
.success(function() { alert(&second success&); })
.error(function() { alert(&error&); })
.complete(function() { alert(&complete&); });
// 在这里执行其他任务
// 为上面的请求设置另一个完成函数
plete(function(){ alert(&second complete&); });
请求 test.php 页面,并一起发送一些额外的数据(同时仍然忽略返回值):
$.post(&test.php&, { name: &John&, time: &2pm& } );
向服务器传递数据数组(同时仍然忽略返回值):
$.post(&test.php&, { 'choices[]': [&Jon&, &Susan&] });
使用 ajax 请求发送表单数据:
$.post(&test.php&, $(&#testform&).serialize());
输出来自请求页面 test.php 的结果(HTML 或 XML,取决于所返回的内容):
$.post(&test.php&, function(data){
alert(&Data Loaded: & + data);
向页面 test.php 发送数据,并输出结果(HTML 或 XML,取决于所返回的内容):
$.post(&test.php&, { name: &John&, time: &2pm& },
function(data){
alert(&Data Loaded: & + data);
获得 test.php 页面的内容,并存储为 XMLHttpResponse 对象,并通过 process() 这个 JavaScript 函数进行处理:
$.post(&test.php&, { name: &John&, time: &2pm& },
function(data){
process(data);
}, &xml&);
获得 test.php 页面返回的 json 格式的内容:
$.post(&test.php&, { &func&: &getNameAndTime& },
function(data){
alert(data.name); // John
console.log(data.time); //
}, &json&);

我要回帖

更多关于 jquery ajax返回值 的文章

 

随机推荐