Ajax 处理json的方法不同

json字符串从从后台传递到前台的方法有两种

1.使用context.Response();

2.使用webmethod 方法调用静态函数 返回的字符串

前者返回的json是obj类型,而后者返回的是json字符串的类型,所以二者在前台的ajax的处理方式不同的。

引用了一下比人写好的例子

 1,使用普通的aspx页面来处理

前段的方法,如果使用ashx还可以添加固定的函数,在url处如“Test.ashx/testfucntion”

$.ajax({ 
                                        type: "post", 
                                        url: "Default.aspx", 
                                        dataType: "json", 
                                        success: function (data) { 
                                                $("input#showTime").val(data[0].demoData); 
                                        }, 
                                        error: function (XMLHttpRequest, textStatus, errorThrown) { 
                                                alert(errorThrown); 
                                        } 
                                });

后台代码这段代码当然是不能发在webmethod下的啦,在ashx中用的时候使用context.response即可

                        Response.Clear(); 
                        Response.Write("[{"demoData":"This Is The JSON Data"}]"); 
                        Response.Flush(); 
                        Response.End();            

 返回的是json的类型

可以直接调用即可

2.使用webservice来处理 

$.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);     
}     
}); 

需要eval('('+data+')')做处理,才能成为obj,但是eval有些漏洞,可以使用第三方的eval

[WebMethod]     
public static string GetDemoData() {     
return "[{"demoData":"This Is The JSON Data"}]";     
}

  


作者:KeithMorning
出处:http://www.cnblogs.com/keithmoring/
关于作者:欢迎转载,且在文章页面明显位置给出原文链接
如有问题,可以通过keith@keithmorning.com 联系我,非常感谢。

原文地址:https://www.cnblogs.com/keithmoring/p/3486129.html