如何打印 xmlhttp 响应

How to print xmlhttp response?

本文关键字:xmlhttp 响应 打印 何打印      更新时间:2023-09-26

我正在从数据库中获取一些信息,这些信息正在恢复为JSON格式,现在我需要打印此JSON信息。但是我的代码不起作用 getCountryDetails.php 是用于与数据库交互的 php 文件。以下代码是脚本,当我单击按钮时,它与数据库相交。

<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>

首先,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);