我从数据库获取一些信息,这些信息现在又回到JSON格式我需要打印这个JSON信息。但我的代码不起作用 getCountryDetails.php 是用于与数据库交互的php文件。下面的代码是脚本,当我单击按钮It与数据库相交时。
<script type="text/javascript">
$(document).ready(function() {
$("#quickSearch").click(function(){
var countries = [];
$.each($("#select-choice-1 option:selected"), function(){
countries.push($(this).val());
});
if (countries == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//myFunction(xmlhttp.responseText);
myFunction(xmlhttp.responseText);
}
}
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","webservices/getCountryDetails.php?q="+countries,true);
xmlhttp.send();
}
});
});
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
答案 0 :(得分:1)
首先,countries
永远不会是空字符串,您已将其定义为数组
var countries = [];
...
if (countries == "") { // always fail
其次,您不能将数组连接成字符串,而XMLHttpRequest不接受数组
xmlhttp.open("GET","webservices/getCountryDetails.php?q=" + countries, true);
第三,你似乎在使用jQuery,所以为什么不使用它,因为它接受一个数组
$.ajax({
url : 'webservices/getCountryDetails.php',
data : countries
}).done(myFunction);