2010-07-25 41 views
0

我在嘗試從this page複製Google圖片搜索。這裏是我的代碼:使用Google圖片搜索API時發生奇怪的JavaScript錯誤

<script type="text/javascript"> 
    <% if @note.text == "" %> 
     google.load("search", "1",{"callback":searchCallback()}); 
    <% else %> 
     google.load("visualization", "1",{"callback":dummyFunction}); 
    <% end %> 

    function se() { 
     var sFormDiv = document.getElementById("searchForm"); 
     var leftScDiv = document.getElementById("leftSearchControl"); 

     this.leftControl = new google.search.SearchControl(); 
     this.searchForm = new google.search.SearchForm(true, sFormDiv); 

     this.searchForm.setOnSubmitCallback(this, se.prototype.onSubmit); 
     this.searchForm.setOnClearCallback(this, se.prototype.onClear); 

     this.leftControl.setResultSetSize(GSearch.LARGE_RESULTSET); 

     var searcher; 
     var options; 

     this.leftControl.addSearcher(new google.search.ImageSearch()); 

     var drawOptions = new google.search.DrawOptions(); 
     drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED); 

     this.leftControl.setNoResultsString(GSearchControl.NO_RESULTS_DEFAULT_STRING); 

     this.leftControl.draw(leftScDiv); 

     this.searchForm.execute("Ferrari"); 

    } 

    // when the form fires a submit, grab its 
    // value and call the left and right control 
    se.prototype.onSubmit = function(form) { 
     var q = form.input.value; 
     if (q && q!= "") { 
     this.leftControl.execute(q); 
     } 
     return false; 
    } 

    // when the form fires a clear, call the left and right control 
    se.prototype.onClear = function(form) { 
     this.leftControl.clearAllResults(); 
     form.input.value = ""; 
     return false; 
    } 

    function searchCallback(){ 
     new se(); 
    } 

    function dummyFunction() { 
    } 

</script> 

當我運行它,我得到這個錯誤:

google.search is undefined 
this.leftControl = new google.search.SearchControl(); 

怎麼可以這樣,如果我通過運行回調的方式獲取到該行搜索API何時加載?謝謝閱讀。

回答

2

How can this be, if I'm getting to that line by way of the callback that is run when the search API is loaded? Thanks for reading.

你是不是傳遞一個回調,但通過把()後立即調用該函數。 searchCallback()依次調用se(),它試圖調用google.search.SearchControl,但google.search在此處未定義,調用undefined上的任何屬性或函數將拋出TypeError

更換

google.load("search", "1",{"callback":searchCallback()}); 

google.load("search", "1",{"callback":searchCallback});