如何发送HttpRequest,并返回Json数据并显示

Ale*_*lex 4 javascript json

我对获取 Json 数据感到非常困惑。如果有任何错误,请纠正我。下面是我的代码:

var xmlhttp;
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)
    {
        var data = JSON.parse(xmlhttp.responseText);
    document.getElementById("getListings").innerHTML=data;
    }
}
xmlhttp.open("GET","https://getJsonData",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.setRequestHeader("Accept", "application/json; charset=utf-8");
xmlhttp.setRequestHeader("Accept-Datetime","Fri, 15 Feb 2013 00:00:00 GMT");
xmlhttp.setRequestHeader("Authorization","XXXXXXX");
xmlhttp.send();
Run Code Online (Sandbox Code Playgroud)

我无法在“getListings”div 上显示任何内容。

mcl*_*sen 5

假设你有 jQuery:

$.ajax({
    type: "GET",
    url: "https://getJsonData",
    dataType: "json",
    success: processData,
    error: function(){ alert("failed"); }
});

function processData(data)
{
    //do something with data
}
Run Code Online (Sandbox Code Playgroud)

另外,不确定您期望将innerHtml 设置为json 对象本身,您可能希望通过使用从json 获取某种属性值 data.someProperty