简体   繁体   中英

jQuery mobile ajax load jsonp not work after page change

I made a mobile webpage with jQuery Mobile. I load the tweets using jQuery's .ajax() method on page load. It works but when I change the page by clicking a link, the tweets won't load anymore.

Here's the HTML:

<ul data-role="listview" data-divider-theme="c" data-inset="true" id="tweets">
    <li data-role="list-divider">Latest Tweets</li>
</ul>

Javascript:

$(document).bind('pageinit',function(){
    $.ajax({
        url:'https://api.twitter.com/1/statuses/user_timeline/LicsonLee.json',
        dataType:'jsonp',
        success:function(data){
            $.each(data,function(i){
                if(i < 5){
                    var tweet = data[i];
                   $('#tweets').append($('<li/>').html('<a href="https://twitter.com/'+tweet.user.screen_name+'/status/'+tweet.id_str+'" data-rel="external"><h4>'+tweet.text+'</h4><p>at '+tweet.created_at+'</p></a>'));
                 }
            });
            $('#tweets').listview('refresh');
        }
    });
});

The page that has problem

Current progress

I've tried Gajotres' answer but it still worked once only. The pages are loaded through AJAX. I also checked that other pages' HTML structure are correct. I still cannot figure out why this is happened.

Any help will be appreciated.

Solution

This should not be used in this case :

$(document).bind('pageinit',function(){

it will trigger only once, instead this should be used:

$(document).bind('pagebeforeshow',function(){

EDIT :

This should do it:

$(document).on('pagebeforeshow', '[data-role="page"]', function(){   

If you want to find out more about this take a look at my ARTICLE , to be more transparent it is my personal blog. Or it can be found HERE .

EDIT 2 :

This solution works:

$(document).on('pageshow',function(){
    $.ajax({
        url:'https://api.twitter.com/1/statuses/user_timeline/LicsonLee.json',
        dataType:'jsonp',
        success:function(data){
            $('#tweets *:not([data-role=list-divider])').remove();
            $.each(data,function(i){
                if(i < 5){
                    var tweet = data[i];
                    $.mobile.activePage.find('#tweets').append($('<li/>').html('<a href="https://twitter.com/'+tweet.user.screen_name+'/status/'+tweet.id_str+'" data-rel="external"><h4>'+tweet.text+'</h4><p>at '+tweet.created_at+'</p></a>'));
                }
            });
            $.mobile.activePage.find('#tweets').listview('refresh');
        }
    });
}); 

Each time you were appending content it was appended to the #tweets at a first page, this will append it only to the currently active page.

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