mui.ajax()和asp.net sql服务器数据交互【1】

时间:2023-03-09 18:12:10
mui.ajax()和asp.net  sql服务器数据交互【1】

简单的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;
                          }
}