我已經問了一些關於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