【问题标题】:My jquery code is not working for changing the page with ajax我的 jquery 代码不适用于使用 ajax 更改页面
【发布时间】:2021-03-23 16:24:28
【问题描述】:

我用 ajax 输入了我的第一个代码,但它没有。请帮忙。 当我单击菜单按钮时,它必须在 menu.txt 中更改部分内容。但是它不起作用。

这是我的 html 代码:

<li id="navMenuButton">
              <a  href="#" onclick="$menu.txt.loadDoc();">
                <span class="glyphicon glyphicon-cutlery"></span><br class="hidden-xs"> Menu</a>
</li>
<section id="homepage">
    <div id="main-content" class="container">  
      <div class="jumbotron">
      </div>
      <div class="row">
.
.
.

这是我的 js 代码:

$(document).ready(function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("#homepage").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "menu.txt", true);
  xhttp.send();
});

【问题讨论】:

  • 你不需要# 只需写document.getElementById("homepage").innerHTML.. 。另外,检查你的浏览器控制台有没有错误? ajax调用成功了吗?
  • 我收到此错误:loadDoc 不是 HTMLAnchorElement.onclick 中的函数
  • 您可以更改您的代码,如this 然后再试一次

标签: javascript html jquery css ajax


【解决方案1】:

.ready() 处理程序采用一个函数来执行一次 DOM 加载。它必须是匿名函数语句或对已声明的命名函数的引用。

关于ajax请求...既然你使用jQuery,我建议你试试jQuery$.ajax()方法。

$(document).ready(function(){ // An anonymous function to pass to the ready handler

  // A named function for the ajax request
  function loadDoc(e){
    e.preventDefault()  // to prevent the normal behavior of the anchor
  
    $.ajax({
      url: "menu.txt",  // make sure the path and filename is correct
      method: "get",  // can be omited because it is the default
      dataType: "html",
      success: function(response){
        $("#homepage").html(response) // the text response passed to the .html() method
      },
      error: function(request, status, error){
        console.log("Status",status,"\nERROR",error)  // If there is an error
      }
    })
  }
  
  // Click handler for the anchor child of #navMenuButton
  $("#navMenuButton a").click(loadDoc)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="navMenuButton">
  <a href="#">
    <span class="glyphicon glyphicon-cutlery"></span>
    <br class="hidden-xs"> Menu</a>
</li>
<section id="homepage"></section>

演示显然不会在这里工作,因为“menu.txt”文件不存在并且因为 SO sn-ps 是阻塞请求。但是你可以看到错误回调被触发了。

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多