JSONP context problem
Posted
by PoweRoy
on Stack Overflow
See other posts from Stack Overflow
or by PoweRoy
Published on 2010-06-16T09:11:36Z
Indexed on
2010/06/16
9:12 UTC
Read the original article
Hit count: 383
JavaScript
|jsonp
I'm using a javascript autocomplete () in a greasemonkey script. On itself it works correctly but I wan't to add JSONP because I want the data from another domain. The code (snippet):
function autosuggest(url)
{
this.suggest_url = url;
this.keywords = [];
return this.construct();
};
autosuggest.prototype =
{
construct: function()
{
return this;
},
preSuggest: function()
{
this.CreateJSONPRequest(this.suggest_url + "foo");
},
CreateJSONPRequest: function(url)
{
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url +'&callback=autosuggest.prototype.JSONCallback';
//newScript.async = true;
newScript.onload = newScript.onreadystatechange = function() {
if (newScript.readyState === "loaded" || newScript.readyState === "complete")
{
//remove it again
newScript.onload = newScript.onreadystatechange = null;
if (newScript && newScript.parentNode) {
newScript.parentNode.removeChild(newScript);
}
}
}
headID.appendChild(newScript);
},
JSONCallback: function(data)
{
if(data)
{
this.keywords = data;
this.suggest();
}
},
suggest: function()
{
//use this.keywords
}
};
//Add suggestion box to textboxes
window.opera.addEventListener('AfterEvent.load', function (e)
{
var textboxes = document.getElementsByTagName('input');
for (var i = 0; i < textboxes.length; i++)
{
var tb = textboxes[i];
if (tb.type == 'text')
{
if (tb.autocomplete == undefined ||
tb.autocomplete == '' ||
tb.autocomplete == 'on')
{
//we handle autosuggestion
tb.setAttribute('autocomplete','off');
var obj1 = new autosuggest("http://test.php?q=");
}
}
}
}, false);
I removed not relevant code. Now when 'preSuggest' is called, it add a script to the header and circumvent the crossdomain problem. Now when the data is received back 'JSONcallback' is called. I can use the data, but when 'Suggest' is I can't use the this.keywords array or this.suggest_url. I think this is because 'JSONcallback' and 'Suggest' are called in a different context.
How can I get this working?
© Stack Overflow or respective owner