[英]Ajax code is not working in html
我正在嘗試通過使用Ajax在onw.html頁面中獲取two.html的所有內容,但是在開發一個頁面應用程序時,總之它不能正常工作。
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// Check browser support
function demo()
{
var name=document.getElementById('dd').value;
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", name);
// Retrieve
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "two.html",
success: function(result){
$("#result").html(result);
}});
});
});
</script>
</head>
<body>
<div id="result"></div>
<input id="dd" type="text" onblur="demo()" >
<br/>
<button>two</button>
<br/>
write something & click on link it will redirect to another page.
close this page and open three.html page.
<br/>
<img src="1.png" alt="da" style="width:150px;height:150px"></img>
</body>
<!DOCTYPE html>
<html>
<body id="body">
<div id="result"></div>
<label>Second Page</label>
<script>
if (typeof(Storage) !== "undefined") {
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
<img src="2.gif" alt="da" style="width:150px;height:150px"></img>
</body>
</html>
Chrome的內部設置阻止了您的請求,因為您沒有使用受支持的方案(例如,http,數據,chrome,chrome-extension,https,chrome-extension-resource)。
簡而言之,您是從桌面運行文件,因此文件地址以file://
開頭,而不是http://
或https://
您需要從服務器設置中以localhost
身份運行文件,或者將文件上傳到遠程服務器。
您還可以使用簡寫版本.get()
簡化代碼。
$(document).ready(function(){
$("button").click(function(){
$.get( "two.html", function( result ) {
$( "#result" ).html( result );
});
});
});
顯然,您也可以在chrome中設置一個標志來覆蓋方案要求 ,但是,最好僅使用正確的方案在服務器上運行文件,如果您確實更改了該標志,請確保在您進行更改時將其還原在本地完成測試,畢竟是有原因的。
在您的控制台上,我可以看到許多錯誤。
所以第一,你需要知道ajax。 如果沒有http或https網址,則Ajax無法使用。 因此,您必須需要啟動localhost或設置任何Web服務器 。
如果要在當前html頁面上加載其他html文件內容 ,則可以使用
$("#results").load("test.html");
但它將僅適用於Firefox瀏覽器,不適用於chrome 。 因為不允許使用chrome-security標志,因此無法從本地文件系統在Web瀏覽器上加載文件。 如果您希望它可以在chrome上運行,則有兩種選擇。
您可以將您的應用程序作為chrome擴展程序。
首先,您可以設置任何本地服務器並啟動localhost,然后將文件復制到www或webapp目錄中,然后嘗試使用Ajax。
如果您已設置第二步,請嘗試此操作。
$("button").click(function(){
/* you can make ajax by 2 ways 1st ways this which used traditionally */
$.ajax({
type:"GET",
url: "two.html",
mimeType: "text/html; charset=utf-8",
success: function(result){
$("#result").html(result);
});
/* 2nd Ajax type is...*/
// $("#result").load("two.html");
});
如果您有Wamp Server,則復制所有文件並粘貼到此目錄“ C:\\ Program Files \\ wamp \\ www \\”上,然后
啟動您的本地主機。
打開瀏覽器並輸入localhost
並選擇您的基本html文件。 然后單擊該按鈕將起作用。
希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.