前台Ajax请求很多时候需要从后台获取JSON格式数据,一般有以下方式:
拼接字符串
returnContent("{"id":"1","name":"A"}");
为了严格符合Json数据格式,对双引号进行了转义。
使用JavaScriptSerialize.Serialize()方法将对象序列化为JSON格式的字符串 MSDN
例如我们有一个匿名对象:
vartempObj=new
{
id=1,
name="A"
}
通过Serialize()方法,返回Json字符串:
stringjsonData=newJavaScriptSerializer().Serialize(tempObj);
returnContent(jsonData);
返回JsonResult类型 MSDN
ASP.NET MVC 中,可以直接返回序列化的JSON对象:
publicJsonResult Index()
{
var tempObj=new
{
id=1,
name="A"
}
returnJson(tempObj, JsonRequestBehavior.AllowGet);
}
需要设置参数‘JsonRequestBehavior.AllowGet',允许GET请求。
前台处理返回的数据时,对于1,2种方法,需要使用JQuery提供的parseJSON方法,将返回的字符串转换为JSON对象:
$.ajax({
url:'/home/index',
success:function(data){
varresult=$.parseJSON(data);
//...
}
});
对于第三种方法,直接作为JSON对象使用即可。
uc浏览器网页版入口官网-手机/电脑uc浏览器网页版入口地址
little fox官方网站入口地址-little fox网页版中国官网入口地址
樱花动漫网官网在线观看入口-樱花动漫网最新网页版入口地址2026
剑桥少儿英语官网入口网址-剑桥少儿英语网页版入口地址
手机百度网盘登录入口地址-百度网盘手机网页版登录入口地址
192.168.1.1无线路由怎么访问?192.168.1.1无线路由器设置登录入口地址