search
HomeWeb Front-endJS TutorialSimple search implementation method based on ajax

Simple search implementation method based on ajax

May 24, 2018 pm 02:23 PM
ajaxaccomplishsearch

This article mainly introduces the simple search implementation method based on ajax. It analyzes in detail the specific steps and related techniques of ajax call to implement the search function in the form of examples. It has certain reference value. Friends in need can refer to it

The example in this article describes a simple search implementation method based on ajax. Share it with everyone for your reference. The details are as follows:

Two .aspx files are used here, one is called Default.aspx and the other is called AjaxOperations.aspx. The first one is used to enter search data, and the latter one is used to Search keywords for processing. There is also a testJs.js file under the js folder, which is the core part of the ajax operation. Yes, code is cheap. Look at the 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:

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; })); 
   }
  }
 }
}

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Analysis on the newline problem of Ajax asynchronous submission data return value

SSH online mall uses ajax to complete the user name Is there an asynchronous verification

Analysis on the order of data returned by ajax request

The above is the detailed content of Simple search implementation method based on ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software