Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX to return JSON - What am I missing?

I am using the SharePoint 2010 REST API, which can return data in either xml or JSON format. For my scenario I need JSON.

Everything is working fine with jQuery:

$.ajax({
     type:"GET",
     url:url,
     dataType:"json",
     success: function(data, textStatus, jqXHR){...}
   });

But I can't get JSON in plain JavaScript, the data is returned as xml. What am I missing?

var XHR=new XMLHttpRequest();
XHR.open("GET", url, true);
XHR.setRequestHeader("Content-Type","application/json");
XHR.onreadystatechange = function () {
if (XHR.readyState == 4 && XHR.status == 200) {...}};
XHR.send(null);
like image 472
Christophe Avatar asked Jun 12 '11 15:06

Christophe


1 Answers

I believe that's a WCF oData service under the hood, which should respect the Accept header.

var XHR=new XMLHttpRequest();
XHR.open("GET", url, true);
XHR.setRequestHeader("Accept","application/json");
XHR.onreadystatechange = function () {
if (XHR.readyState == 4 && XHR.status == 200) {...}};
XHR.send(null);
like image 145
Dave Ward Avatar answered Oct 08 '22 00:10

Dave Ward