[英]Sample AJAX call not working
嘗試做一個簡單的 AJAX 調用(自學)。 我在與html
相同的文件夾中有一個.txt
文件。 我在這里做錯了什么? 謝謝。
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#poo").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({
type: "GET",
url: "data.txt",
data: "",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
}
});
});
});
</script>
</head>
<body>
<form id="poo">
<input type="text"> </input>
<input type="submit"> </input>
</form>
<br>
<br>
<div style='display: none;'>
<p id="foo">this shows</p>
</div>
<a href="page.html">Start Over</a>
</body>
</head>
</html>
這是一個方便的函數,它通過 AJAX 加載遠程文件,並使用.innerHTML()
將其加載到 jQuery 選擇器中的任何元素中。
// Does the exact same thing as the entire block of code you wrote..
// These jQuery methods are chainable so you can do this in 1 statement.
$("#foo") // Contains the DOM reference,
// so no need to use getElementById().
.load("data.txt") // Loads "data.txt" into "#foo".
.show(); // Makes "#foo" visible.
相關的:
根據您的評論,您還有其他一些問題。
你說你不確定是否加載了 jQuery。 jQuery 只是 javascript,因此您可以將它包含在<script></script>
標簽中。 最簡單的方法是使用jQuery 的 CDN 。 單擊鏈接,然后選擇所需的版本和格式。 將有一個包含腳本標簽的彈出窗口,只需將其復制到頁面中,最好在頁面上的任何其他 Javascript 之前。 如果您不確定要使用哪個版本/格式, v1.x, minified是您要走的路。
你提到你在本地運行它。 問題是,Javascript 不應該直接訪問您的文件系統。 它將嘗試通過http
協議請求文件,而沒有服務器軟件,您只能通過file://
協議請求文件。
互聯網上有無數關於此的主題,但要解決它,您應該安裝服務器。 XAMPP是一個不錯的選擇,它是跨平台的。 下載它,您的應用程序將在您的所有瀏覽器中運行。 當您將其上傳到服務器時,它也將在您的瀏覽器中工作
嘗試添加dataType: "text"
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.