开发者

Jquery load data from URL or go to URL

I have 2 php pages named "personal_info" and "portfolio". I load them via php functions in codeigniter http://www.mysite.com/controller/personal_info and http://www.mysite.com/controller/portfolio.

I have a page with menu tabs linked to personal_info and portfolio and I want to load the pages via ajax when a tab is clicked. If js is turned off in the browser the tabs should just go to the url.

I am using the jquery .load() function to load the pages.

<script type="text/javascript">     
$(document).ready(function(){
    $('#persona开发者_开发百科l_info').click(function() {
        $('#result').load('personal_info #load'); //load fragments from #load div
    }); 

    $('#portfolio').click(function() {
        $('#result').load('portfolio #load');
    });         
});
</script>

HTML

<div id="tab"><a href="http://www.site.com/portfolio/edit/general_info" id="general_info">General Info</a></div>

<div id="tab"><a href="http://www.site.com/portfolio/edit/portfolio" id="portfolio">Portfolio</a></div>

<div id="result"></div>

Issue: When I click on a tab it treats it as a link and goes to the URL instead of loading the page via jquery. How can I disable the link if javascript is on? Also, I noticed that javascript is not loaded from fragments in the pages, and if I put the javascript in the page I load data it doesn't pick it up.

What is a good solution for this?

EDIT:

For loading js, I just wrapped the entire page in the result div and am loading the other pages with the js and header, footer.


For the first issue: put return false; at the end of each 'click' function:

$('#personal_info').click(function() {
    $('#result').load('personal_info');
    return false;
}); 

Edit: For the second issue, maybe pull out any jquery/javascript and run it from a central application.js file?


You need to prevent the default action of the <a/> element. You can accomplish this by using event.preventDefault()

$('#personal_info').click(function(e) {
    $('#result').load('personal_info');
    e.preventDefault();
}); 

$('#portfolio').click(function(e) {
    $('#result').load('portfolio');
    e.preventDefault();
});         


To stop the default action from occurring (following the link) you need to use return false at the end of your jQuery click() functions.

With regard to your second issue ("javascript is not loaded from the [dynamically loaded] pages"), ensure that you are using jQuery's .live functionality to attach handlers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜