提交不过两大类,表达提交与ajax提交
一:表单提交
html
<form action="TestWebspx.aspx" method="post"> <input type="text" name="username"/> <input type="submit" value="submit"/> </form>后台获取提交的数据并返回前台
public partial class TestWebspx : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string username = Request["username"]; Response.Write("your input:" + username); } }
二:Ajax处理
方法一:
前端
var kmtcb = {} kmtcb.search = function () { var qyport = $("#qyport").val(); var carrier = $("#carrier").val(); var number = $("#number").val(); $.ajax({ url: "get_b.aspx?act=Search", type: "post", data: { qyport: qyport, carrier: carrier,number:number}, success: function (result) { var dataObj = eval("(" + result + ")");//转化成json对象 alert(dataObj.Carrier); alert(dataObj.Qyport); alert(dataObj.Number); }, error: function (result) { console.log(result); alert(result); } }) }后端
public void Search() { string qyport = Request["qyport"]; string carrier = Request["carrier"]; string number = Request["number"]; T t = new T(); t.Carrier = "1234"; t.Qyport = "aaaa"; t.Number = "yunjia001"; string jsonstr = JsonConvert.SerializeObject(t); Response.Clear(); Response.Write(jsonstr); Response.End(); }
方法二:
$(function () { $.ajax({ type: "post", url: "TestWebspx.aspx/TestJson", contentType: "application/json;charset=utf-8", data: "{'msg':'hello'}",// data: { key: '123', type: 'S' } dataType: "json", success: function (result) { var dataObj = eval("(" + result.d + ")"); alert(dataObj.msg); } }); })这里是因为微软框架默认返回一个 { "d": "后台返回的数据" } 的数据
所以取我们自己返回的json对象时需要用result.d而且需要eval传化成json对象,或者使用jquery的 $.parseJSON("str");
后台
[WebMethod] public static string TestJson(string msg) { return "{msg:123}"; }后台方法一定要是静态的且必须加上[WebMethod]特性否者抛出异常
此时post请求没有问题,但如果需要修改成get方式就会出现
只需要加后台方法上加上[ScriptMethod(UseHttpGet = true)]特性
[WebMethod] [ScriptMethod(UseHttpGet = true)] public static string TestJson(string msg) { return "{msg:123}"; }
http://www.cnblogs.com/acles/articles/2385648.html