XMLHTTPREQUEST response with JSON in Javascript?

Sebastian Chacon picture Sebastian Chacon · Apr 5, 2012 · Viewed 7k times · Source

I've a problem. I try to send a JSON request to a web server XBMC. I can see in Wireshark the POST Request is sent correctly and the response is sent by the web server but, in Javascript, I can't take the JSON Data to show it in a alert.

var xhr_object = null;

   if(window.XMLHttpRequest) // Firefox
      xhr_object = new XMLHttpRequest();
   else if(window.ActiveXObject) // Internet Explorer
      xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
   else { // XMLHttpRequest non supporté par le navigateur
      alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
      return;
   }

   xhr_object.open("POST", "http://"+add+":9000/jsonrpc", false);

   xhr_object.onreadystatechange = function() {
      if(xhr_object.readyState == 4)
      var json = xhr_object.responseText;
         alert(xhr_object.responseType)
         alert("("+json+")");
   }
   xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   var data = '{"jsonrpc": "2.0", "method": "Input.Up", "id": "1"}';
   xhr_object.send(data);

Answer

Hemesh Singh picture Hemesh Singh · Apr 5, 2012

I'll suggest you to use some javascript framework e.g. jQuery. Have a look at http://api.jquery.com/jQuery.getJSON/ and http://api.jquery.com/jQuery.ajax/.

You won't need to write that much of javascript if you use jQuery's ajax function.