這為的環境是asp.net用c#。這個很常見的問題是:如果要把參數傳到後台,甚至是後台與前台共享傳入參數,這個程式怎麼寫最簡潔?請看以下寫法:
這個檔名叫做ApiInput.aspx.cs
這個程式碼的功能是把參數用Request傳入到參數,這裡用response.write加入script的寫法有時也會在除錯中看到。(在測試二該行)
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Configuration; public partial class ApiInput : System.Web.UI.Page { public string aa; public string bb; protected void Page_Load(object sender, EventArgs e) { aa = Request.QueryString["aa"]; bb = Request.QueryString["bb"]; //Response.Write("<script>alert('測試二:"+ aa + "," + bb +"');</script>");//測試二 } }
這個檔名叫做ApiInput.aspx,是ApiInput.aspx.cs的前端,使用前要配合上面的程式碼,如果不需要後端程式碼的話,可以參考隔壁有前端單獨傳入參數的教學文。下面這段程式是讀入後台的全域變數,由於已經有傳入值,前台也可以看到傳入參數(在測試三該行)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ApiInput.aspx.cs" Inherits="ApiInput" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title><script type="text/javascript"> var aa = "<%=aa%>"; var bb = "<%=bb%>"; alert("測試三:" + aa + " " + bb);//測試三 </script> </head> <body> <form id="form1" runat="server"> <div></div> </form> </body> </html>
兩種方法都可以傳入參數,可以自由選擇後端或者前端,是很常用的小技巧。
文章標籤
全站熱搜