前面讲过AJAX如何传入JSON数据(http://www.jb51.cc/article/p-kaqozsfh-mx.html),接着就是后台如何接收并处理了。下面通过一个实例的展示就一目了然了。
前端代码:
<script src="jquery-1.8.0.min.js" type="text/javascript"></script> <script type="text/javascript"> var user = { name:"BiXin",age:25,weight:135 }; $(function () { $.ajax({ url:"server.aspx",type: "post",data: JSON.stringify(user),headers: { Accept: "application/json","Content-Type": "application/json" },processData: false,success:function(data,textStatus,jqXHR){ } }); }); </script>
后台代码(这里引用了Newtonsoft来做JSON数据的反序列化,具体可以百度下Newtonsoft的使用方法,dll文件下载地址http://james.newtonking.com/json):
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections.Specialized; using System.IO; using Newtonsoft.Json; namespace OAJAX { public partial class server : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { StreamReader sr = new StreamReader(Request.InputStream); string userStr = sr.ReadToEnd(); User user = JsonConvert.DeserializeObject<User>(userStr); ; // 接着对User对象做处理。。。 Response.End(); } } public class User { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } private int weight; public int Weight { get { return weight; } set { weight = value; } } } }
部分运行结果截图:
原文链接:https://www.f2er.com/ajax/164771.html