2016-01-21 44 views
0

在外部服務器上有一個由一些.html文件組成的文件夾,其中一個是index.html。

服務器可以在他的url中加載:foldername或foldername/index.html。 在每個html文件中加載一個js文件。 現在的問題是,我的服務器的遠程json文件存在於{filename} .json。 這個概念工作正常,但是當我第一次加載沒有index.html的文件夾名時,index.json文件似乎不被使用。

在刷新頁面(F5)或首次打開頁面後,使用激活的開發人員工具查看console.log,它可以正常工作。 這是谷歌瀏覽器和FF測試。

下面是相關代碼:

//test if url ends with :html 
var loc = window.location.pathname.split('/'); 
var last = loc[loc.length-1] || loc[loc.length-2]; 

//if not take index.json as file name 
if(!last.match(/html/)){ 
    var file_json = "index.json"; 
} 
else{ 
    var file_json = last.replace(/html/,"json"); 
} 
var URL = base + "/" + file_json; 
$.ajax({ 
    xhrFields: { 
    withCredentials: false 
    }, 
    type: "GET", 
    url: URL 
    }).done(function (data) { 
    ... 
    } 
console.log(data); 
+0

你把你的腳本放在$(document).ready下面嗎? –

+0

這裏的問題在哪裏?你的代碼完全符合你的解釋。你想與衆不同? – Gavriel

+0

@Gavriel比這是個問題。我不是jquery/js佈道家!當代碼加載並立即計算數據時出錯,這是我的問題。錯誤代碼!? – maen

回答

0

把所有上面的代碼到一個功能:

function myCode(){ 
    // all the above code comes here 
} 

,並呼籲myCode();每當你想它運行。例如:你可能會想要運行它,例如:

<input type="button" value="Click me!" onclick="myCode();"/> 
+0

THX供您評論,但約書亞H是對的。我拿了一張$ document.ready,現象就消失了。但是,無論如何謝謝你! – maen