2016-05-12 111 views
-1

试图做一个简单的AJAX调用(自学)。我在与html相同的文件夹中有一个.txt文件。我在这里做错了什么?谢谢。示例AJAX调用不起作用

<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> 
+0

您是否在控制台中看到错误?你是在服务器上运行还是在本地计算机上运行? –

+0

是的,在我的Chrome控制台:'未捕获的ReferenceError:$未定义'的第一行'$(document).ready(function(){' – Kervvv

+0

您是否包含jQuery库? – Naterade

回答

1

这是通过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's CDN。点击链接,然后选择你想要的版本和格式。会弹出一个包含脚本标签的弹出窗口,只需将它复制到页面中,最好是在页面上有任何其他Javascript之前。如果您不确定要使用哪种版本/格式,则需要v1.x,缩小为


你提到你在本地运行它。问题是,Javascript不应该直接访问你的文件系统。它将尝试通过http协议请求文件,而无需服务器软件,只能通过file://协议请求文件。

在互联网上有很多的话题,但要解决它,你应该安装一台服务器。 XAMPP是一个很好的,它是跨平台。下载它,你的应用程序将在你所有的浏览器中运行。当您将其上传到服务器时,它也可以在您的浏览器中工作

+0

谢谢你的帮助!我还必须在Safari中打开才能看到我的浏览器没有遇到任何问题(请参阅原始问题评论) – Kervvv

+0

@ceuskervin - 我已经更新了答案,并提供了解决问题所需的所有相关信息。按我的答案打勾。 :) –

+0

@ Pamblam-感谢您的详细解答。它工作完美。 – Kervvv

0

尝试添加dataType: "text"

$.ajax({ 
    type: "GET", 
    url: "data.txt", 
    dataType: "text", 
    success: function(data){ 
     $("#foo").html(data); 
     document.getElementById("foo").style.display = 'block'; 
     alert('hey'); 
    })