2013-06-28 220 views
0

我想要在加載頁面時將一些內容加載到我的div中,但是隨後我想擁有將加載新內容的按鈕,並替換當前DIV中的內容。使用Ajax和Jquery加載內容

這是我的HTML:

<a id="aboutlink" href="#">About</a> 
<a id="infolink" href="#">Info</a> 
<div id="contentbox">Starting content</div> 

這是我的javascript:

$(document).ready(function(){ 
    $('#aboutlink').click(function(){ 
     $('#contentbox').load('/includes/about-info.html'); 
    }); 
    $('#testlink').click(function(){ 
     $('#contentbox').load('/includes/test-info.html'); 
    }); 
}) 

http://jsfiddle.net/spadez/GCg4V/1/

我只是想知道我做錯了,因爲當我想這是我的服務器上它沒有加載任何內容。我還想知道是否有更好的方式來實現這樣的事情,因爲它似乎並不像我可以做任何加載綁定到它。

感謝您給予的任何幫助或建議。

+5

1)'testlink'!='infolink' 2)加上'event.preventDefault()',以確保您的鏈接不會進入行動 – mishik

+0

請求是否成功?您是否使用Chrome開發者工具或類似工具進行了檢查(當然它不工作在jsFiddle,因爲這些資源不存在那裏) – MasterScrat

+0

確保'load('/ includes/about-info.html')'有合適的路徑 – cinek

回答

1

load方法將只設置第一個匹配元素的HTML如果狀態(200 OK) ..如果是除此之外,像(404 Not Found)(403 Forbidden),那麼它不會將HTML ..

要設置它,無論迴應如何,請嘗試編輯jsFiddle

1

第一次嘗試這樣的事:

$.get('/includes/test-info.html', data, function(data){alert(data);}) 

然後你就可以看到正在返回什麼。

0

好吧,那麼運行此代碼檢查什麼發生在那裏:

<script src="http://code.jquery.com/jquery-latest.min.js"type="text/javascript"></script> 

<script>  
    $(document).ready(function() { 
     $('#aboutlink').click(function() { 
      $('#contentbox').load('/includes/about-info.html', function(response, status, xhr){ 
       if (status == "error") { 
        var msg = "Sorry but there was an error: "; 
        $("#error").html(msg + xhr.status + " " + xhr.statusText); 
       } 
      }); 
     }); 
     $('#infolink').click(function() { 
      $('#contentbox').load('/includes/test-info.html', function(response, status, xhr){ 
       if (status == "error") { 
        var msg = "Sorry but there was an error: "; 
        $("#error").html(msg + xhr.status + " " + xhr.statusText); 
       } 
      }); 
     }); 

    }) 
</script> 
<a id="aboutlink" href="#">About</a> 
<a id="infolink" href="#">Info</a> 
<div id="contentbox">Starting content</div> 
<div id="error"></div> 
+0

問題不在於錯字.. 。即使使用正確的id名稱,當響應不是'200 OK'時它也不會工作。 –

+0

@MiroMarkarian:檢查新代碼以檢查發生了什麼。 –

0

我認爲它是與您如何指定負載的URL。 試着這麼做

$(document).ready(function() { 
$('#aboutlink').click(function() { 
     $('#contentbox').load('includes/about-info.html'); 
    }); 
    $('#infolink').click(function() { 
     $('#contentbox').load('includes/test-info.html'); 
    }); 
}) 

沒有前導 「/」