利用ajax实现前台javascript同c#后台MVC下的aspx.cs文件传递数据的两种方法

xiaoxiao2021-02-28  8

方法一:

通过jquery传递数据:

jquery代码:

function buttonClick(){ $(function () { $.ajax({ type: 'post', url: 'Default.aspx?method=Send2', cache:false, success: function (data) { if (data == '00000') { alert(data); } else { alert(data); } } }); }); } Default.aspx.cs 文件中接收 jquery 传递过来的数据:

c#代码:

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { string result = ""; if(Request["method"] != null) { try { switch (Request.QueryString["method"]) { case "Send2": result = Send2(); break; } } catch(Exception ex) { result = ex.Message; } Response.Clear(); Response.ContentType = "text/plain"; Response.Write(result); Response.End(); } } protected string Send2() { return "success"; } } 方法二:

通过 javascript 交换JSON数据:

javascript 代码:

var obj; function buttonClick() { var i = "aaa"; var xmlhttp1 = new XMLHttpRequest(); xmlhttp1.open("GET", "Default.aspx?q="+i, "true"); xmlhttp1.onreadystatechange = RequestCallBack; xmlhttp1.send(null); function RequestCallBack() { if (xmlhttp1.readyState == 4) { var json1 = xmlhttp1.responseText; obj = JSON.parse(json1); magazineGrid.innerHTML = null; for (var js2 in obj){ alert(obj[js2].STATION_NAME); } } } } c#代码:

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["q"] != null) { string restr1 = Button1_Click(); System.Diagnostics.Debug.WriteLine(restr1); Response.Write(restr1); Response.End(); } } protected string Button1_Click() { return "'STATION_NAME':'success'"; } }

转载请注明原文地址: https://www.6miu.com/read-1600047.html

最新回复(0)