簡單的ajax和asp.net的交互,例如遍歷數據,前端顯示復雜內容沒有添加代碼,可自行研究!非常適合懂那么一點點的我們!
實現步驟:
1、APP前端HTML:
<div class="mui-input-row">
<label>賬號:</label>
<input id="name" type="text" placeholder="請輸入賬號">
</div>
<button id="btnLogin" type="button" class="mui-btn mui-btn-blue mui-btn-block">點擊獲取密碼</button>
<div id="div">這里顯示從服務器獲取到的密碼</div>
2、APP前端JavaScript:
mui.init();
mui.ready(function() {
var btnLogin = document.getElementById("btnLogin");
var names=document.getElementById("name");
btnLogin.onclick = function() {
var url="http://localhost/myStudy/APP/Handler.ashx"; //AJAX的url,把asp.net下的Handler.ashx用瀏覽器打開,復制地址即可
mui.post(url, {
name:names.value, //向asp.net下的Handler.ashx傳遞數據
}, function(data) {
//服務器返回響應,根據響應結果,分析是否登錄成功;
var jsonstr = JSON.stringify(data); //將data(后台獲取的result字符串,相當於JavaScript的值)轉化為json字符串
//console.log(jsonstr);
var jsonobj=JSON.parse(jsonstr); //將json字符串轉化為JavaScript對象
//console.log(jsonobj);
var divinner=document.getElementById("div");
divinner.innerHTML=jsonobj.password;
}, 'json');
};
});
3、asp.net 配置web.config:<system.webServer>節點下添加
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="X-Requested-With"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
(據說是為了支持跨域)
4、asp.net創建新文件夾,添加新項一般處理程序 Handler.ashx;
public SqlConnection getcon()
{
string M_str_sqlcon = "Server=(local);Initial Catalog=userlogin ;Uid=sa ;Pwd=sa ;";
SqlConnection myCon = new SqlConnection(M_str_sqlcon);
return myCon;
}
DataTable mytable = new DataTable();
public DataTable gettable(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
sqlda.Fill(mytable);
sqlcon.Close();
sqlcon.Dispose();
return mytable;
}
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
string name = context.Request.Params["name"]; //獲取前端傳過來的數據
string strsql= "select password from login where username = '"+name+"'"; //查詢數據庫
DataTable dt = gettable(strsql); //獲取DataTable
if (dt.Rows.Count > 0 && dt != null)
{
string result = "{\"password\":\"" + dt.Rows[0]["password"].ToString() + "\"}"; //設置字符串result,此處為JavaScript的值,需要前端將這個值轉化為json字符串
context.Response.Write(result); //給前端傳遞字符串result
}
}
public bool IsReusable {
get {
return false;
}
}