我是AJAX和Jquery的新手,我想要做的是在点击一个按钮时在我的第一个体内显示第二个HTML文件。到目前为止我没有运气,单击按钮时没有任何反应。所有html文件都与我的index.html在同一目录中。关于我做错了什么想法?
这是我网站上的导航,我的函数调用名为callPage的AJAX
<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');
}
});
}
});
答案 0 :(得分:0)
您需要在$(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>
或者您可以使用click
绑定活动addEventListener
并将网址存储到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>