我已经问了一些关于ajax的问题,但我仍然没有得到它。jquery/AJAX功能不起作用
我拿了一个脚本,我在互联网上找到并做了一些修改,但它没有奏效!
HTML:
<a data-toggle="team" id="times">TEAM</a>
原创剧本:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>
修改后的脚本:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('#times').click(function(e) {
$("#loading").show();
var href = $(this).attr("data-toggle");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
$.ajax({
url: 'ajaxcontdent/ajax'+url,
type: 'GET',
error: function(){
// always good to have an error handler with AJAX
},
success: function(data){
$('#content').html(data);
}
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
};
</script>
什么是错的w ^我的脚本?什么都没发生。我点击我的<a>
链接,没有任何东西。我已经尝试将文件位置放在href
属性上,但e.preventDefault();
不起作用,我的网站就像没有AJAX一样运行。
在原始代码中,作者使用了一些content.php
文件。但我不知道JSON,所以我不知道他在那个文件中放了什么。
控制台中没有错误。
我ajaxcontent/ajaxteam.php
文件内容:
<p style="color:#fafafa;">Team</p>
这确实只是一条线。只是一个测试。
什么这个脚本在做什么?你真正的问题是什么?添加预期的输出。 – PHPExpert
没有任何反应。我点击我的''链接,什么也没有。除非我将文件位置放在'href'属性上,但是AJAX不起作用。 – Igor
你的'ajaxcontdent/ajaxteam'看起来怎么样? – madalinivascu