【发布时间】:2011-02-12 04:51:40
【问题描述】:
我有一个搜索表单,其中数据库查询已用 php 编码,html 文件通过 ajax 调用此 php 文件以在搜索表单中显示结果。问题是,我希望结果以与 search.html 相同的形式显示;然而,当 ajax 工作时,它会转到 search.php 来显示结果。
搜索.html:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="scripts/search_ajax.js" type="text/javascript"></script>
</head>
<body>
<form id="submitForm" method="post">
<div class="wrapper">
<div class="field">
<input name="search" id="search" />
</div><br />
<input id="button1" type="submit" value="Submit" class="submit" onclick="run_query();" /><br />
</div>
<div id="searchContainer">
</div>
</form>
</body>
</html>
如果我将 action="search.php" 添加到表单标签,它会在 search.php 上显示结果。我希望它显示在同一个表单上[即search.html,而不是search.php],如果我只是添加javascript函数[如上所述],它不会在search.html上显示任何内容。
search_ajax.js:
var xmlHttp
function run_query() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("This browser does not support HTTP Request");
return;
} // end if
var url="search.php";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("searchContainer").innerHTML=xmlHttp.responseText;
} //end if
} //end function
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// For these browsers: Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//For Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} //end function
搜索.php:
<?php
include 'config.php';
$search_result = "";
$search_result = $_POST['search'];
$result = mysql_query("SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE '%$search_result%' ORDER BY idQuotes DESC", $conn)
or die ('Error: '.mysql_error());
【问题讨论】:
标签: php javascript html ajax forms