[英]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.