0
我在一个greasemonkey脚本中使用javascript autocomplete()。本身它工作正常,但我不想添加JSONP,因为我想从另一个域的数据。 代码(片段):JSONP上下文问题
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);
我去掉不相关的代码。现在,当调用'preSuggest'时,它会向头添加一个脚本并绕过跨域问题。现在,当接收到数据时,会调用'JSONcallback'。我可以使用这些数据,但是当'Suggest'是我不能使用this.keywords数组或this.suggest_url。我认为这是因为'JSONcallback'和'Suggest'是在不同的上下文中调用的。
我该如何得到这个工作?
你的第一个示例创建一个新的自动提示对象,但我想保留其他数据(如suggest_url)的“旧”对象。我为页面上的每个输入元素创建了多个自动建议对象。还有其他解决方案吗? – RvdK 2010-06-16 09:43:29
没有为你需要的每个对象创建全局变量,然后让他们知道一个名字,以便他们可以引用自己(例如:var as1 = new autosuggest(); as1.name ='as1';'然后我不能真的想想现在的任何事情,也许你可以重新设计架构,以便不需要持久的AS对象? – nickf 2010-06-16 13:15:40