[英]How to stop xmlhttp.open duplicating the entire page? (ajax livesearch)
我正在使用一個簡單的“實時搜索”腳本,該腳本在用戶在文本框中鍵入內容時顯示MySQL數據庫的結果。 如果Javascript指向完全獨立的頁面,則效果很好,但是我需要它指向同一頁面。 不幸的是,當我嘗試執行此操作時,頁面會在生成結果時在自身內部重復。
這按預期工作:
Document called: "test.php" containing JavaScript below and test2.php containing the PHP code
xmlhttp.open("GET","test2.php?livesearch="+str,true);
xmlhttp.send();
這將在頁面內創建一個頁面:
Document called: "test.php" containing both the JavaScript and PHP code below
xmlhttp.open("GET","?livesearch="+str,true);
xmlhttp.send();
我知道這是因為它正在循環中打開自己,但是我不確定為避免這種情況我應該在代碼中進行哪些更改。 任何幫助將不勝感激,因為我在Google上找不到太多幫助。
這是我所有的代碼:
Java腳本
function showResult(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","&livesearch="+str,true);
xmlhttp.send();
}
PHP代碼
if(isset($_GET['livesearch'])) {liveSearch();}
function liveSearch() {
$q=$_GET["livesearch"];
$sqlQuery = "SELECT * FROM something WHERE something LIKE '%" . $q . "%' ;
etc etc etc
}
您為什么要代碼指向自身? 擁有一個只返回所需內容的Web服務似乎合乎邏輯。 就像您不必重復編寫代碼一樣,只需采用一些通用的方法將整個頁面或Web服務中的內容吐出來。
如果需要調用同一頁面,則始終可以使用正則表達式來提取所需的內容,而不用替換整個頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.