简体   繁体   中英

jQuery refreshing specific div

So I have a sortable li list that has a series of pages displayed.

When I sort them, my jQuery code calls a php page that updates the order of my pages in the database.

On the same page as the list, it displays the pages in the order they are in but I want to be able to auto update this order right after my database is updated without actually refreshing the page.

So basically, secretly "refresh" the pageContainer div.

What is the best way to do this?

<div id="pageContainer">
   <!-- include() a series of pages in the right order from database -->
</div>

 $("#pageContainer").sortable({
    stop : function(event, ui){
        var postData = $(this).sortable('serialize');
        var url = "saveOrder.php";
        $.ajax({
            type: "POST",
            url: url,
            data: postData,
            success: function(data) { $('#pageContainer').html(data);  }
        });
    }
});

EDIT So a simple $('#pageContainer').html(data); did the trick but my $('form').on('input propertychange change') stopped working. The fix is on this page if anyone wants to look.

Create your sorted content on the php page just add that result to proper div.

so basically..

$("#pageContainer").sortable({
    stop : function(event, ui){
        var postData = $(this).sortable('serialize');
        var url = "saveOrder.php";
        $.ajax({
            url: url,
            data: postData,
            success: function(data) {  
            jQuery("#pageContainer").html(data);}
        });
    }
});

If you echo out the HTML you want in your saveOrder.php page, then the rest is simple:

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    contentType: 'html',
    success: function(data) { 
        $('#pageContainer').html(data);
    }
});

Depending on your version of jQuery (v1.5+), you may wish to take advantage of the jQuery Promise that $.ajax returns. Your code would change to:

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    contentType: 'html'
}).done(function(data) {
    $('#pageContainer').html(data);
});

This allows you to chain callbacks and keeps your setup separate from your callback functions. For example, you could do this:

...
}).done(function(data) {
    $('#pageContainer').html(data);
}).fail(function() {
    alert('failed :(');
}).always(function() {
    alert('done!');
});

you would have your ajax call return html like

dataType: 'html'

Then in your success function you would do

$('#pageContainer').html(data);

用“ delegate”代替“ on”怎么样?

$('#pageContainer').delegate('form', 'input propertychange change', function(){...;})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM