[英]jQuery is working in Firefox only, not in Chrome or IE
我正在嘗試使用 jQuery 使用另一個 html 文件中的內容加載 html 文件的一部分。 這些代碼在 Mozilla Firefox 上運行良好,但不適用於 Google Chrome 或 Windows Internet Explorer。 在最后兩個瀏覽器中,頁面保持原樣。 我究竟做錯了什么?
索引.html
<html>
<head>
<script src="jquery-3.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#clickhere").click(function(){
$("#partialdisplay").load("sourcepage.html");
});
});
</script>
</head>
<body>
<div id="header">
This is the header.
<a href="#" id="clickhere">Click here</a>
</div>
<div id="partialdisplay">
<!--Content from other page will be loaded here -->
</div>
<div id="footer">
This is the footer.
</div>
</body>
</html>
源頁面.html
<html>
<head>
</head>
<body>
<div id="partialdisplay">
This part will be called back to index.html.
</div>
</body>
</html>
如果使用離線頁面,Chrome(即我不知道)不支持讀取本地文件。您可以通過三種方式檢查:
在使用這些命令之前,請務必結束所有正在運行的 Chrome 實例。
在 Windows 上:
chrome.exe –allow-file-access-from-files
在 Mac 上:
打開 /Applications/Google\\ Chrome.app/ --args --allow-file-access-from-files
更改您的代碼:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <script src="jquery-3.1.1.js"></script> <script type="text/javascript"> var sourcecontent = '<div id="partialdisplay">This part will be called back to index.html.</div>'; $(document).ready(function(){ $("#clickhere").click(function(){ $("#partialdisplay").html(sourcecontent); }); }); </script> </head> <body> <div id="header"> This is the header. <a href="#" id="clickhere">Click here</a> </div> <div id="partialdisplay"> <!--Content from other page will be loaded here --> </div> <div id="footer"> This is the footer. </div> </body> </html>
Chrome 以及其他一些瀏覽器不允許跨源請求,底線是如果其來源不受信任,它將不會加載文件(在您的情況下,這里直接從磁盤加載文件)。 您可以通過使用 python(使用一些未使用的端口,如 1234)運行一個簡單的 http 服務器來繞過此安全檢查。 將您的文件傳輸到一個單獨的目錄中,然后在其中運行以下命令。
Linux/Mac :
python -m SimpleHTTPServer 1234
窗戶:
python -m http.server 1234
您現在可以使用http://localhost:1234訪問您的應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.