javascript - 基于页面上多个链接的链接文本的Ajax mysql查询

标签 javascript php mysql ajax

我的页面上有一些链接。当用户单击链接时,它会使用 mysql 查询的 WHERE 子句中的链接文本,并使用 ajax 将结果返回到页面。

我需要多个 id 或类来运行不同的查询。我尝试过使用多个 id 的 querySelectorAll(见下文)以及使用多个类的 getElementsByClassName(),但查询在 WHERE 子句中返回未定义对于这两者。

不过,我可以使用 getElementById 让它在一个链接上工作。

我做错了什么?

HTML:

<ul>
    <li><a id="spquery" onclick='ajaxFunction()'>John</a></li>
    <li><a id="spquery1" onclick='ajaxFunction()'>Jill</a></li>
</ul>
<div id='ajaxDiv'>Results will display here</div>

Javascript:

<script languspquery="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest; 

 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }catch (e){
     // Something went wrong
     alert("Your browser broke!");
         return false;
      }
   }
 }

 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }
// below you can see I'm using querySelectorAll with multiple ids
 var spquery = document.querySelectorAll('#spquery, #spquery1').text;
 var queryString = "?spquery=" + spquery ;
 ajaxRequest.open("GET", "/the-bootstrap/ajax-ped.php" + queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>

来自/the-bootstrap/ajax-ped.php 的 mysql 查询

$spquery = $_GET['spquery'];
$query = "SELECT * from people";
$query .= " WHERE personname = '$spquery'";

最佳答案

querySelectorAll 将返回一个节点数组。要使用每个节点的值,您需要像这样迭代数组

var arr_spquery = document.querySelectorAll('#spquery,#spquery1');
var spquery = '', sep='';
for(var i=0,len=arr_spquery.length; i<len; i++) {
spquery += sep + arr_spquery[i].innerHTML;
sep = ',';
}
console.log(spquery);  /* optional - to log the value */

var queryString = "?spquery=" + spquery ;
ajaxRequest.open("GET", "/the-bootstrap/ajax-ped.php" + queryString, true);
ajaxRequest.send(null);

然后在服务器端的 php 脚本中,您可以根据需要使用该字符串。 :)

关于javascript - 基于页面上多个链接的链接文本的Ajax mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011795/

相关文章:

javascript - req.body 不适用于快速路由器发布请求

mysqldump 提示密码,即使凭据保存在/home/user/.my.cnf

mysql - SQL 查询关于 union 和 concat

php - Php SQLITE 中的分页

php - MySQL:新闻的多张照片和视频连接

php - 用 Volley 发送参数并获得响应

mysql - 在创建带有迁移的表时设置外键约束 Sequelize

javascript - 在完成 Rxjs Observable 之前,如何等待 subscribe 中定义的异步方法?

javascript - 字符串中的乱码文本 - 出现数字

javascript - 增加 Qualtrics slider 值框的宽度