2011-06-03 71 views
0

我得到了一個網頁,其中包含一些自制搜索引擎,它應該在服務器端文本文件中查找一些數據。我用JS來解析這個文件,除了第一次使用它以外,它工作得很好...罪魁禍首似乎是我的fetchText()函數,它不會在第一次返回任何東西。請注意,如果我在fetchText()內部添加alert(),它會正常工作(請參閱JS源代碼中的註釋)。我想IFRAME沒有完全加載或什麼的。我能做什麼 ?JavaScript文本文件閱讀器第一次不工作

網頁代碼

 <form style="margin-top:15px; margin-left:15px;width:200px;"> 
      <input type="text" value="NGR_" id="srcTxtInput" style="margin-top:0px;margin-left:0px;width:100px;"/> 
      <input type="button" value="Go" onclick="SearchString('./Coordinates.txt')" /> 
     </form> 


    <div id="searchResults" style="vertical-align:right;margin-top:25px;"> 
     <select size="4" id="select_list" onchange="Selec_change();" ondblclick="Selec_change();" style="visibility: hidden; width:250px;margin-left:8px;" ></select>      
     <img id="closeImg" src="./close.png" height="15px" width="15px" style="opacity:0.5;visibility:hidden; margin-left:235px;margin-bottom:5px;margin-top:5px;vertical-align:top;" alt="Close results" title="Close results" onclick="HideSearch();" onmouseover="this.style.cursor='pointer';"/> 
    </div> 

JS代碼

function SearchString(txtFile){ 
    var slist = document.getElementById('select_list'); 
    var str = trim(document.getElementById('srcTxtInput').value.toUpperCase()); 

    if(str == ""){ 
     slist.options.length = 0; //empty list 
     HideSearch(); 
     exit; 
    } 

    var txt = fetchText(txtFile); 

//DO SOMETHING 
} 



function fetchText(txtFile) { 

var d = document; 
var txtFrame = d.getElementById('textReader'); 
txtFrame.src = txtFile; 

**//Note that if I add *alert(txtFrame.src)* here the function works the 1st time** 

var text = ''; 
if (txtFrame.contentDocument) { 
    var d = txtFrame.contentDocument; 
    text = d.getElementsByTagName('BODY')[ 0].innerHTML; 
} 
else if (txtFrame.contentWindow) { 
    var w = txtFrame.contentWindow; 
    text = w.document.body.innerHTML; 
} 

return text; 
} 

回答

0

由於這樣的裝載頁面內容是一個異步操作,你不能指望內容立即在那裏在設置的「src」屬性後。您必須將通過文本搜索的代碼放入框架文檔的「加載」事件處理程序中。

這意味着你會寫是這樣的:

fetchText(textFile, function(theText) { 
    // DO SOMETHING 
    }); 

和修改 「fetchText()」 更是這樣的:

function fetchText(txtFile, whenLoaded) { 
    var d = document; 
    var txtFrame = d.getElementById('textReader'); 

    txtFrame.onload = function() { 
    var text = ''; 
    if (txtFrame.contentDocument) { 
     var d = txtFrame.contentDocument; 
     text = d.getElementsByTagName('BODY')[ 0].innerHTML; 
    } 
    else if (txtFrame.contentWindow) { 
     var w = txtFrame.contentWindow; 
     text = w.document.body.innerHTML; 
    } 

    whenLoaded(text); 
    }; 

    txtFrame.src = txtFile; 
}