我的页面上有一些链接。当用户单击链接时,它会使用 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/