Alex
Alex

Reputation: 12191

How to send HttpRequest, and it returns Json data and display it

I got very confused on getting Json data. Please correct me if anything does wrong. Below is my code:

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();

I could not get anything displayed on "getListings" div.

Upvotes: 4

Views: 16124

Answers (2)

James Black
James Black

Reputation: 41838

I see a couple of issues:

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

You should use:

xmlHttp.setRequestHeader('Content-Type', 'application/json')

But, I would go with httpRequest.setRequestHeader('Accept', 'application/json'); as this tells the server you want to accept JSON, yours states you are sending JSON.

Now, when you parse the JSON, you may want to look at this: Parse JSON in JavaScript? as not all browsers can parse JSON.

Now, when you parse, you will want to look at not just putting it into the innerhtml, but format it and then put the formatted html code into the innerhtml if you desire.

A simple way to see if you are parsing it properly is to have an alert just show one property in the json.

Upvotes: 0

mclaassen
mclaassen

Reputation: 5138

Assuming you have jQuery:

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

function processData(data)
{
    //do something with data
}

Also, not sure what you're expecting just setting the innerHtml to the json object itself, you probably want to get some sort of propery value form the json by using data.someProperty

Upvotes: 5

Related Questions