最近在使用jquery的ajax方法时,需要返回的数据为json数据,在success返回中数据处理会根据返回方式不同会采用不同的方式来生成json数据。在$.ajax方法中应该是如何来处理的,简单进行说明。
首先给出要传的json数据:[{demodata:this is the json data}]
1,使用普通的aspx页面来处理
$.ajax({ 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/json; charset=utf-8, success: function (data) { $(input#showtime).val(eval('(' + data.d + ')')[0].demodata); //这里有两种对数据的转换方式,两处理方式的效果一样 //$(input#showtime).val(eval(data.d)[0].demodata); }, error: function (xmlhttprequest, textstatus, errorthrown) { alert(errorthrown); } });
下面这里为asmx的方法代码
public static string getdemodata() { return [{\demodata\:\this is the json data\}]; }
这里的这种处理方式就把传递回来的json数据当成了字符串来处理的,所在就要对这个数据进行eval的处理,这样才能成为真正的json对象数据。
即
success:function(data){ eval(data); }
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
ajax怎么处理服务器返回的数据类型
ajax请求webservice跨域的实现方法(附代码)
以上就是ajax后台success上传的json数据如何处理的详细内容。