在没有JQuery的情况下在客户端显示JSON服务器响应

时间:2019-01-18 19:48:01

标签: javascript node.js ajax express

我正在尝试创建一个获取服务器响应(JSON)并在不使用JQuery的情况下在网页列表中显示JSON信息的函数。那怎么可能?

;

有了邮递员,我得到以下“ GET”正文:

filterGet: function () {
        var ajax = new XMLHttpRequest();

        ajax.onreadystatechange=function() {
            if (ajax.readyState==4 && ajax.status==200)
            {

                var ul = document.getElementById("results");
                while(ul.firstChild){
                    ul.removeChild(ul.firstChild);
                }

                //i am trying to get the JSON response from the server
                var array = ajax.response;



                var i;
                for(i=0;array.length;i++){

                    var latitudeForm = array[i].Latitude;
                    var longitudeForm = array[i].Longitude;
                    var nameForm = array[i].TagName;
                    var hashForm = array[i].HashName;

                    var newli = document.createElement('li');
                    newli.className = "tagListElements";
                    newli.innerText = nameForm + "("  + latitudeForm + ","
                        + longitudeForm + ")" + hashForm;
                    ul.appendChild(newli);
                }

            }
        }

        ajax.open('GET', "/test1" , true);
        ajax.setRequestHeader("Content-Type", "application/json");
        ajax.send();
    }

The output is just for presentation purposes

简单地说,我想实现以下目标,但不使用JQuery:

[
{
    "Latitude": "45.01379",
    "Longitude": "4.390071",
    "TagName": "Casel",
    "HashName": "#begaiburje"
},
{
    "Latitude": "59.01379",
    "Longitude": "7.390071",
    "TagName": "Casel",
    "HashName": "#ne"
}
]

2 个答案:

答案 0 :(得分:0)

如果我理解您的问题,则希望使用“ innerHtml”将json响应放入HTML页面内。

参考:

javascript - Using innerHTML to display JSON/object data in a certain div - Stack Overflow

JSON XMLHttpRequest

答案 1 :(得分:-1)

您不需要使用Content-type请求标头。而是在打开XHR和发送XHR之间,您应按照此文档设置ajax.responseType = 'json'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType

没有设置responseType的情况下,默认返回类型为纯文本,因此您也可以将其保留为原样,只需在回调中添加JSON.parse即可将字符串JSON转换为对象。 。但是当responseType存在时为什么要这样做? :D

相关问题