繁体   English   中英

AJAX返回结果加上整个页面内容(使用Javascript,PHP,MySQL但不是JQuery)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM