[英]AJAX returning a javascript to be parsed results in loss of page contents
[英]AJAX returning results plus the entire page contents (Using Javascript, PHP, MySQL but not JQuery)
我在我的網站上運行了一個AJAX腳本,它應該在上一個下拉菜單onchange事件發生后更新一個依賴的下拉菜單(一個SELECT選項菜單)。
當我點擊第一個下拉列表時,第二個下拉列表似乎填充了MySQL數據庫查詢中的正確值。 但是,根據我的價值觀,我似乎也在整個HTML網頁上提取內容。
我想知道如何只在我的SELECT選項菜單中再次加載整個網頁時引入我的值。
我的Javascript:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp_aris=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp_aris=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_aris.onreadystatechange=function()
{
if (xmlhttp_aris.readyState==4 && xmlhttp_aris.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp_aris.responseText;
}
}
xmlhttp_aris.open('GET','http://mywebdomain.com?ajax=true&q='+str,true);
xmlhttp_aris.send();
}
</script>
我的PHP代碼:
// begin my ghetto code
if ($_GET['ajax'] == 'true') {
$q = $_REQUEST["q"];
$con = mysqli_connect('localhost','db_user','db_pass','db_name');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql='SELECT DISTINCT
employees.firstName,
employees.lastName
FROM
sales_reps
INNER JOIN employees ON sales_reps.employeeId = employees.employeeId
INNER JOIN sales_campaign ON sales_campaign.salesCampId = sales_reps.saleCampId
WHERE
sales_campaign.marketId = '.$q.' AND
employees.isactive = 1';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['firstName'] . '">'
. htmlentities($row['firstName']) .' '.htmlentities($row['lastName']) .'</option>';
}
mysqli_close($con);
}
// end my ghetto code
我的代碼在頁面上帶有下拉菜單:
<select id="frm-marketid" name="frm-marketid" onchange="showUser(this.value)">
<option value="">Choose a Market</option>
<option value="74">Annapolis</option>
<option value="61">Anne Arundel</option>
<option value="26">Aventura</option>
<option value="63">Baltimore</option>
</select>
<br/>
<select id="txtHint"><b>Person info will be listed here.</b></select>
只需在輸出ajax響應后終止你的腳本
...
}
mysqli_close($con);
exit;
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.