PDA

View Full Version : XHR, JSON and Twitter Error code 0


eddjc
03-09-2010, 03:36 PM
Hey all,

For some reason this is always returning error code 0:

function twit(ident) {

this.ident = ident;
this.url = "http://www.search.twitter.com/search.json";
this.params = { q:"from%3Aeddjc",
rpp: 20 }

this.loadObject = new JSONLoader(this.ident + "Loader", this, this.url, this.params);

this.result;

this.init = function() {

this.loadObject.init();

objectTracker.trackObject(this);

this.loadObject.load();

}

this.onSuccess = function(paramsArray) {
this.result = paramsArray;
alert("loaded");

}
this.notify = function (message) {
alert(message);

}
}

function JSONLoader(ident, caller, url, params) {

this.ident = ident;
this.xhr;
this.caller = caller;

this.url = url;
this.params = params;


this.init = function () {

if (window.XMLHttpRequest)
{
this.xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

this.xhr.onreadystatechange = function () {

if(this.readyState == 4) {

if(this.status == 200) { objectTracker.tracking.loadObject.doLoad(); }
else window.console.log("Loader: Loader Error code " + this.status);
}
}
}

this.load = function () {
this.loadGet(this.url, this.params, this.caller);
}

this.loadPost = function (file, params, caller) {

this.caller = caller;

this.caller.notify("Processing...");


this.xhr.open('POST', file, false);
this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.xhr.setRequestHeader("Content-length", this.formatParams(params).length);
this.xhr.setRequestHeader("Connection", "close");

this.xhr.send(this.formatParams(params));


}



this.loadGet = function (file, params, caller) {




filestring = file + "?" + this.formatParams(params);
this.caller.notify(filestring);

this.xhr.open('GET', filestring, true);
this.xhr.send(null);


}

this.formatParams = function (array) {
var result = "";
var x = 0;

for (key in array) {
if (x != 0) result += "&";

result += key + "=" + array[key];

x++;
}


return result;
}


this.doLoad = function () {

if (this.xhr.responseText != '') {

paramsArray = eval(this.xhr.responseText);
this.caller.onSuccess(paramsArray);
}
else alert("Error loading");




}

}

I'm guessing it's because it's not a local file - any body got any ideas?

Many thanks
Edd

A1ien51
03-09-2010, 07:43 PM
The XMLHttpRequest Object can not be used across different domains.

You need to use JSONP (http://en.wikipedia.org/wiki/JSON#JSONP)

Eric

eddjc
03-10-2010, 07:47 AM
Hey - awesome, thanks!

Best
Edd