I need part of the page to be changed dynamically with ajax

前端 未结 2 958
忘掉有多难
忘掉有多难 2020-12-21 10:18

I just finished wireframing and need to dynamically change main part of the page which is a div class=\"container\" with sliced parts of the page which represent other conte

2条回答
  •  庸人自扰
    2020-12-21 10:51

    Usually, what I do is create a route handler full of url hashes mapped to urls. That way, when I listen for a window hashchange event, I can route to that hash's corresponding url. The object would look like this:

    var router = {
        "#ajax" : "http://fiddle.jshell.net"
    };
    

    Then I use this object to acquire html from the url asynchronously, using the router and a jquery get request (on hashchange):

    $(window).on("hashchange", function(){
        var route = router[location.hash];
        if (typeof route === 'undefined') return;            
        $.get( route, function( data ) {
            $( ".sliderContent" ).html( data );
        });                
    });
    

    As you can see from the jquery get's callback, the ajax data retrieved is injected into the DOM in the sliderContent div. I hope this helps :)

    See the working jsfiddle here: http://jsfiddle.net/zrLLhq30/5/

    Edit: the AJAX takes a little while to process, so give it a bit of time to load.

    UPDATE

    I've updated my fiddle to include multiple links (as well as replacing the jquery get with a jquery load, just to speed up the resource retrieval) and, as you can see, the content inside the divs load into the container without a page refresh.

    If you implement the solution they way I did, using different hashes for each resource URL, then it should work great. I hope this is what you meant :)

    Updated jsfiddle here: http://jsfiddle.net/zrLLhq30/7/

提交回复
热议问题