Simple search implementation method based on ajax
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 != 'undefined') { 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 = ''; }; cell.onmouseover = function() { this.style.backgroundColor = '#E8F2FE'; }; 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:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxOperations.aspx.cs" Inherits="WebTest2008.AjaxOperations" %>
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[] { '#' })); } } } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

In the era dominated by intelligence, office software has also become popular, and Wps forms are adopted by the majority of office workers due to their flexibility. At work, we are required not only to learn simple form making and text entry, but also to master more operational skills in order to complete the tasks in actual work. Reports with data and using forms are more convenient, clear and accurate. The lesson we bring to you today is: The WPS table cannot find the data you are searching for. Why please check the search option location? 1. First select the Excel table and double-click to open it. Then in this interface, select all cells. 2. Then in this interface, click the "Edit" option in "File" in the top toolbar. 3. Secondly, in this interface, click "

The mobile Taobao app software provides a lot of good products. You can buy them anytime and anywhere, and everything is genuine. The price tag of each product is clear. There are no complicated operations at all, making you enjoy more convenient shopping. . You can search and purchase freely as you like. The product sections of different categories are all open. Add your personal delivery address and contact number to facilitate the courier company to contact you, and check the latest logistics trends in real time. Then some new users are using it for the first time. If you don’t know how to search for products, of course you only need to enter keywords in the search bar to find all the product results. You can’t stop shopping freely. Now the editor will provide detailed online methods for mobile Taobao users to search for store names. 1. First open the Taobao app on your mobile phone,

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:
