代码之家  ›  专栏  ›  技术社区  ›  RvdK

JSONP上下文问题

  •  0
  • RvdK  · 技术社区  · 14 年前

    代码(代码段):

    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);
    

    我怎样才能让它工作?

    1 回复  |  直到 14 年前
        1
  •  0
  •   nickf    14 年前

    this 因此,当返回JSONP调用时,它正在调用 autosuggest.prototype.JSONCallback 但是这个函数不能调用 this.suggest()

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

    function JSONCallback(data) {
        var as = new autosuggest();
        as.keywords = data;
        as.suggest();
    }
    

    autosuggest 对象并将其用作回调:

    var globalAS = new autosuggest("http://example/?q=");
    
    // inside the CreateJSONPRequest function, change this line:
    newScript.src = url +'&callback=globalAS.JSONCallback';