Ajax在HTML主体中显示HTML页面



我是Ajax和jQuery的新手,我要做的是在单击按钮时在我的第一个按钮时显示第二个HTML文件。到目前为止,我还没有运气,当按下按钮时什么都没有。所有HTML文件均与我的index.html相同的目录。关于我做错了什么的想法?

这是我的网站中的导航,我的功能调用了ajax name callPage

<div class="top-bar-left">
        <ul class="dropdown menu" data-dropdown-menu>
            <li> <a onclick="callPage('login.html')">Login</a></li>
            <li><a onclick="callPage('register.html')">Register</a></li>
            <li><a onclick="callPage('guide.html')">Guide</a></li>
        </ul>
      </div>
$(document).ready(function(){
    function callPage(pageRefInput){
        $.ajax({
            url:pageRefInput,
            type: "GET",
            dataType:'text/html',
            success:function(response){
                console.log('ok',response);
                $('.content').html(response);
            },
            error: function(error){
                console.log('err',error);
            },
            complete:function(xhr,status){
                console.log('complete');
            }
        });
    }
});

您需要从$(document).ready(function(){...})

中声明您的功能

function callPage(pageRefInput) {
  console.log(pageRefInput)
  /*$.ajax({
    url: pageRefInput,
    type: "GET",
    dataType: 'text/html',
    success: function(response) {
      console.log('ok', response);
      $('.content').html(response);
    },
    error: function(error) {
      console.log('err', error);
    },
    complete: function(xhr, status) {
      console.log('complete');
    }
  });*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-bar-left">
  <ul class="dropdown menu" data-dropdown-menu>
    <li> <a onclick="callPage('login.html')">Login</a></li>
    <li><a onclick="callPage('register.html')">Register</a></li>
    <li><a onclick="callPage('guide.html')">Guide</a></li>
  </ul>
</div>

或者您可以使用addEventListener绑定事件click并将URL存储到data-attribute

$(document).ready(function() {
  document.querySelectorAll('a').forEach((a) => {
    a.addEventListener('click', callPage);
  });
});
function callPage(e) {
  e.preventDefault();
  var url = this.dataset.url;
  console.log(url);
  /*$.ajax({
    url: pageRefInput,
    type: "GET",
    dataType: 'text/html',
    success: function(response) {
      console.log('ok', response);
      $('.content').html(response);
    },
    error: function(error) {
      console.log('err', error);
    },
    complete: function(xhr, status) {
      console.log('complete');
    }
  });*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-bar-left">
  <ul class="dropdown menu" data-dropdown-menu>
    <li> <a data-url='login.html'>Login</a></li>
    <li><a data-url='register.html'>Register</a></li>
    <li><a data-url='guide.html'>Guide</a></li>
  </ul>
</div>

最新更新