【发布时间】:2010-10-05 05:37:24
【问题描述】:
我在greasemonkey 脚本中使用了javascript 自动完成()。它本身可以正常工作,但我不想添加 JSONP,因为我想要来自另一个域的数据。 代码(sn-p):
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”。我可以使用数据,但是当“建议”是我不能使用 this.keywords 数组或 this.suggest_url。我认为这是因为“JSONcallback”和“Suggest”在不同的上下文中被调用。
我怎样才能让它工作?
【问题讨论】:
标签: javascript jsonp