JSONP上下文问题

时间:2010-06-16 09:11:37

标签: javascript jsonp

我在greasemonkey脚本中使用了javascript autocomplete()。它本身工作正常,但我不想添加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'在不同的上下文中被调用。

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:0)

当您直接调用原型上的函数时,this没有上下文,因此当返回JSONP调用时,它正在调用autosuggest.prototype.JSONCallback,但该函数无法调用{{1} }}

相反,我建议创建一个包装函数:

this.suggest()

或创建一个全局function JSONCallback(data) { var as = new autosuggest(); as.keywords = data; as.suggest(); } 对象并将其用作回调:

autosuggest