ajax讀取資料庫資料程式碼例項

admin發表於2018-07-31

既然ajax可以向後臺傳送請求,也可以傳遞引數,當然就可以根據需要進行資料庫查詢功能。

下面就通過程式碼例項介紹一下如何實現此需求,當然程式碼比較簡單,僅作為參考之用。

程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<style>
body{
  font-size:12px;
}
</style>
<script>
function loadXMLDoc(keywords) {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  }
  else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("show").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("get", "demo/ajax/net/Query.aspx?keywords=" + escape(keywords), true);
  xmlhttp.send();
}
window.onload = function () {
  var otxt = document.getElementById("txt");
  var obt = document.getElementById("bt");
  obt.onclick = function () {
    loadXMLDoc(otxt.value);
  }
}
</script>
</head>
<body>
<input type="text" id="txt"/>
<input type="button" id="bt" value="檢視效果"/>
(例如輸入:css教程或者div教程)
<div>結果:<span id="show"></span></div>
</body>
</html>

在文字框中輸入要查詢的課程名稱,然後點選按鈕即可實現查詢效果。asp.net後臺程式碼如下:

[C#] 純文字檢視 複製程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Configuration;
 
namespace ajax
{
    public partial class Query : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          string keywords = Server.UrlDecode(Request.QueryString["keywords"]);
          if (String.IsNullOrEmpty(keywords.Trim()))
          {
              Response.Write("輸入查詢關鍵詞");
              Response.End();
          }
          string connString=ConfigurationManager.ConnectionStrings["access_con"].ConnectionString;
          string configPath=ConfigurationManager.ConnectionStrings["access_path"].ConnectionString;
          string conPath = HttpContext.Current.Server.MapPath(configPath);
          OleDbConnection conn = new OleDbConnection(connString + conPath);
             
          string sql = "select * from data where type='" + keywords + "' order by id desc";
          OleDbCommand cmd = new OleDbCommand(sql,conn);
          try
          {
              conn.Open();
 
              OleDbDataReader MyReader = cmd.ExecuteReader();
 
              if (MyReader.Read())
              {
                  Response.Write("存在指定教程");
              }
              else
              {
                  Response.Write("不存在指定教程");
              }
          }
          catch (Exception ex)
          {
              throw (ex);
          }
          finally
          {
              conn.Close();
          }
      }
    }
}

相關文章