Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Created July 30, 2012 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerrishotts/3209074 to your computer and use it in GitHub Desktop.
Save kerrishotts/3209074 to your computer and use it in GitHub Desktop.
My XHR and JSON
PKUTIL.loadQueue = Array();
PKUTIL.XHRinProgress = false;
PKUTIL.XHRTimer = -1;
PKUTIL.load = function(theFileName, aSync, completion)
{
if (device.platform != "WinCE")
{
PKUTIL._load(theFileName, aSync, completion);
return;
}
console.log("Pushing request to load XHR: " + theFileName);
PKUTIL.loadQueue.push(function()
{
console.log("Processing XHR " + theFileName);
PKUTIL._load(theFileName, aSync, completion);
});
if (PKUTIL.XHRTimer < 0)
{
PKUTIL.XHRTimer = setInterval(PKUTIL._XHRQueue, 100);
}
}
PKUTIL._XHRQueue = function()
{
if (PKUTIL.XHRinProgress)
{
return;
}
if (PKUTIL.loadQueue.length > 0)
{
var f = PKUTIL.loadQueue.pop();
f();
}
}
PKUTIL._load = function(theFileName, aSync, completion)
{
if (!window.XMLHttpRequest)
{
if (completion)
{
completion(PKUTIL.COMPLETION_FAILURE, "This browser does not support XMLHttpRequest.");
return;
}
}
PKUTIL.XHRinProgress = true;
var r = new XMLHttpRequest();
r.onreadystatechange = function()
{
if (r.readyState == 4)// loaded
{
if (r.status == 200 || r.status == 0)// success
{
if (completion)
{
console.log("success loading " + theFileName + ", length " + r.responseText.length);
completion(PKUTIL.COMPLETION_SUCCESS, r.responseText);
PKUTIL.XHRinProgress = false;
}
} else// failed to load
{
if (completion)
{
completion(PKUTIL.COMPLETION_FAILURE, r.status);
PKUTIL.XHRinProgress = false;
}
}
}
}
if (device.platform == "WinCE" && theFileName.substr(0, 4) != "http")
{
r.open('GET', "/app/www/" + theFileName, true);
} else
{
r.open('GET', theFileName, aSync);
}
r.send();
}
/**
*
* Retrieves a JSON string from the specified URL, and executes completion.
* Completion must be of the form ( success, data ).
*
* @param theURL the URL or Filename
* @param completion function of the from ( success, data )
*
*/
PKUTIL.loadJSON = function(theURL, completion)
{
PKUTIL.load(theURL, true, function(success, data)
{
var theParsedData =
{
};
if (success)
{
try
{
theParsedData = JSON.parse(data);
} catch (err)
{
console.log("Failed to parse JSON from " + theURL);
success = COMPLETION_FAILURE;
}
}
// call completion, if available
if (completion)
{
completion(success, theParsedData);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment