Maison  >  Article  >  interface Web  >  Méthode de mise en œuvre de recherche simple basée sur ajax

Méthode de mise en œuvre de recherche simple basée sur ajax

亚连
亚连original
2018-05-24 14:23:152249parcourir

Cet article présente principalement la méthode d'implémentation de recherche simple basée sur ajax. Il analyse en détail les étapes spécifiques et les techniques associées de l'appel ajax pour implémenter la fonction de recherche sous forme d'exemples. Il a une certaine valeur de référence. référez-vous à lui

L'exemple de cet article décrit une méthode simple d'implémentation de recherche basée sur ajax. Partagez-le avec tout le monde pour votre référence, les détails sont les suivants :

Deux fichiers .aspx sont utilisés ici, l'un s'appelle Default.aspx et l'autre s'appelle AjaxOperations.aspx. Le premier est utilisé pour saisir. rechercher des données, et ce dernier est utilisé pour rechercher des mots-clés à traiter. Il existe également un fichier testJs.js sous le dossier js, qui constitue la partie essentielle de l'opération ajax. Oui, le code est bon marché. Regardez le code :

testJs.js

// 此函数等价于document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
// 创建 XMLHttpRequest对象,以发送ajax请求 
function createXMLHTTP() {
 var xmlHttp = false;
 var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
       "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
       "Microsoft.XMLHTTP"];
 for (var i = 0; i < arrSignatures.length; i++) {
  try {
   xmlHttp = new ActiveXObject(arrSignatures[i]);
   return xmlHttp;
  }
  catch (oError) {
   xmlHttp = false; //ignore
  }
 }
 // throw new Error("MSXML is not installed on your system."); 
 if (!xmlHttp && typeof XMLHttpRequest != &#39;undefined&#39;) {
  xmlHttp = new XMLHttpRequest();
 }
 return xmlHttp;
}
function addAjaxSearch() {
 inputField = $("txtSearch");
 completeTable = $("suggestTb");
 completep = $("popup");
 completeBody = $("suggestBody");
 var tempStr = inputField.value;
 // alert(tempStr);
 var keyWord = encodeURI(tempStr);
 if (tempStr == "")
  return;
 var xmlReq = createXMLHTTP();
 xmlReq.open("post", "AjaxOperations.aspx?searchKeyword=" + keyWord, true);
 xmlReq.onreadystatechange = function() {
  if (xmlReq.readyState == 4) {
   if (xmlReq.status == 200) {
    //xmlReq.responseText为输出的那段字符串
    setNames(xmlReq.responseText);
   }
   else {
    alert("Connect the server failed!");
   }
  }
 }
 xmlReq.send(null);
}
// 设置p中的表格数据
function setNames(names) {
 if (names == "") {
  clearNames();
  return;
 }
 clearNames(); // 清空p中已有的的表格数据
 setOffsets(); // 设置p到合适的位置
 var row, cell, txtNode;
 var s = names.split("#");
 for (var i = 0; i < s.length; i++) { // 显示类似search下拉选择项
  var nextNode = s[i];
  row = document.createElement("tr");
  cell = document.createElement("td");
  cell.onmouseout = function() { this.style.backgroundColor = &#39;&#39;; };
  cell.onmouseover = function() { this.style.backgroundColor = &#39;#E8F2FE&#39;; };
  cell.onclick = function() { completeField(this); }; // 搜索框设置为选择的数据
  cell.pop = "T";
  txtNode = document.createTextNode(nextNode);
  cell.appendChild(txtNode);
  row.appendChild(cell);
  $("suggestBody").appendChild(row);
 }
}
// 清空p中已有的的表格数据
function clearNames() {
 completeBody = $("suggestBody");
 var ind = completeBody.childNodes.length;
 for (var i = ind - 1; i >= 0; i--) {
  completeBody.removeChild(completeBody.childNodes[i]);
 }
 completep = $("popup");
 completep.style.border = "none";
}
// 设置p到合适的位置
function setOffsets() {
 completeTable.style.width = inputField.offsetWidth; +"px";
 var left = calculateOffset(inputField, "offsetLeft");
 var top = calculateOffset(inputField, "offsetTop") + inputField.offsetHeight;
 completep.style.border = "black 1px solid";
 completep.style.left = left + "px";
 completep.style.top = top + "px";
}
function calculateOffset(field, attr) {
 var offset = 0;
 while (field) {
  offset += field[attr];
  field = field.offsetParent;
 }
 return offset;
}
// 搜索框设置为选择的数据
function completeField(cell) {
 inputField.value = cell.firstChild.nodeValue; // 搜索框设置为选择的数据
 clearNames(); //清空p中已有的的表格数据
}
//用来设置当鼠标失去焦点后文本框的隐藏
document.onmousedown = function() {
 if (!event.srcElement.pop)
  clearNames();
} //填写输入框

Default.aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest2008.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Ajax Search</title>
 <script src="js/testJs.js" type="text/javascript"></script>
 <style type="text/css" media="screen">
  body
  {
   font: 11px arial;
  }
  .suggest_link
  {
   background-color: #FFFFFF;
   padding: 2px 0px 2px 0px;
   border:solid 1px #cceeff;
  }
  .suggest_link_over
  {
   background-color: #E8F2FE;
   padding: 2px 0px 2px 0px;
  }
  #search_suggest
  {
   position: absolute;
   background-color: #FFFFFF;
   text-align: left;
   border: 1px solid #000000;
  }
 </style>
</head>
<body>
 <input name="txtSearch" id="txtSearch" type="text" class="suggest_link" onkeyup="addAjaxSearch();" maxlength="200" style="width: 200px" /> 
 <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" title="Run Search" />
 <p id="popup" style="position: absolute">
  <table id="suggestTb" cellspacing="0" cellpadding="0" bgcolor="#fffafa" border="0">
   <tbody id="suggestBody">
   </tbody>
  </table>
 </p>
</body>
</html>

Default.aspx.cs :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
 public partial class Default : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
  {
  }
 }
}

AjaxOperations .aspx:

4784cc8617a2795dfb46f310286bec69

AjaxOperations .aspx.cs :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
 public partial class AjaxOperations : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
  {
   if (!string.IsNullOrEmpty(Request["searchKeyword"]))
   {
    string tempStr = Request["searchKeyword"];
    /* 测试用 实际项目中可以对数据库进行检索等等相关操作,这里简化了 */
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(tempStr + " #");
    sb.Append("#");
    sb.Append(tempStr += " " + tempStr);
    sb.Append("#");
    sb.Append(tempStr += " " + tempStr);
    Response.Write(sb.ToString().TrimEnd(new char[] { &#39;#&#39; })); 
   }
  }
 }
}

Ce qui précède est ce que j'ai compilé pour vous. J'espère que cela vous sera utile à l'avenir.

Articles connexes :

Exemple d'analyse du problème de retour à la ligne de la valeur de retour des données de soumission asynchrone Ajax

Le centre commercial en ligne SSH utilise ajax pour compléter le nom d'utilisateur Y a-t-il une vérification asynchrone

Analyse sur l'ordre des données renvoyées par requête ajax

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn