成功的AJAX响应

时间:2020-05-27 22:14:24

标签: javascript php json ajax

我在AJAX中的功能有问题。 我创建了对返回JSON的PHP文件的AJAX调用。

对于此JSON循环,我创建了一个功能,如果AJAX成功,则该功能将运行。 但是实际上数据是空的。

    <script>
    document.getElementById("getproducts").addEventListener("submit", sendAjax);
    function sendAjax(event) {
    var q = document.getElementById('search').value;
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                display(this.responseText);
            }
        }
        xhttp.open("POST", "results.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send('search='+q);
        event.preventDefault();
    }

    function display( jsdata ){
        for ( var key in jsdata ){
            var htmltabel = '';
            var datanode = document.createElement("div");
            htmltabel += '<div class="id">' + jsdata[key]['id']    + '</div>';
            content    = htmltabel;
            datanode.innerHTML = content;
            document.getElementById("resultt").appendChild(datanode);
        }
    }
    </script>

如果我在这样的函数中编写JSON硬编码,那一切都会好起来的。

var hardcoded = {"1736":{"id":"1736","post_title":"Test explode","_sku":"12345","_stock":null,"_price":"9.50"}}
//PART OF THE CODE
if (this.readyState == 4 && this.status == 200) {
    display(hardcoded);
}

如何解决此问题,该功能使用响应的JSON?

1 个答案:

答案 0 :(得分:0)

这是一个更正的脚本,您只需将responseData从string转换为Json Object

document.getElementById("getproducts").addEventListener("submit", sendAjax);
    function sendAjax(event) {
    var q = document.getElementById('search').value;
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                display( JSON.parse(this.responseText) ); // You should convert the response from string to a valid JSON
            }
        }
        xhttp.open("POST", "results.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send('search='+q);
        event.preventDefault();
    }

    function display( jsdata ){
        for ( var key in jsdata ){
            var htmltabel = '';
            var datanode = document.createElement("div");
            htmltabel += '<div class="id">' + jsdata[key]['id']    + '</div>';
            content    = htmltabel;
            datanode.innerHTML = content;
            document.getElementById("resultt").appendChild(datanode);
        }
    }