Need advice on pushState and onpopstate

I use ajax to not download all the content of the page, and to do the job on the button, I use pushStateand onpopstateas follows:

function get_page(args){
    ....
    $.ajax({ 

        url     : '/ajax/search?' + param  ,  type : 'get', 
        success : function(data) {   

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

                    window.history.pushState( { url: '/ajax/search?' + param  }
                    , "" , '/search?' + param  );
        },  
    });
}

window.onpopstate = function(e) {

    if ( e.state == null ){
        location.href = location.href ;
        return;
    }

    $.ajax({ url     : e.state.url , type : 'get', 
        success : function(data) {   
            $('#search_aj').html(data); 
        },      
    });     
};

This works, but I think that my code is not very good, because I repeat the success code in Ajax, and if I make changes in one, I have to change it in another. and code ( e.state == null )is the best way to return to the first page?

Are there any tips you can give me to improve my code?

+4
source share
3 answers

If you have many similar small requests in a script, you can control it in a function that will do the job.

function makeRequest(url, successHandler) {
  $.get(url, function(data) {
    $('#search_aj').html(data);

    successHandler && successHandler();
  });
}

function get_page(args) {
  //...
  var historyURL = '/search?' + param;
  var reqURL = '/ajax' + historyURL;

  makeRequest(reqURL, function() {
    window.history.pushState({
      url: reqURL
    }, '', historyURL);
  });
}

$(window).on('popstate', function(e) {
  if (e.state)
    makeRequest(e.state.url);
  else
    location.href = location.href;
});
Nothing here, sorry.
Run codeHide result

jQuery , .get .ajax, GET request. jQuery .on native addEventListener, DOM, .

+1

ajax. DRY.

function get_page(args){
    ....
    $.ajax({ 

        url     : '/ajax/search?' + param  ,  type : 'get', 
        success : function(data) {   
            populateSearch(data);
                window.history.pushState( { url: '/ajax/search?' + param  }, "" , '/search?' + param  );

        },  
    }); 

}




window.onpopstate = function(e) {

    if ( e.state == null ){
        location.href = location.href ;
        return;
    }

    $.ajax({ url     : e.state.url , type : 'get', 
        success : function(data) {   
            populateSearch(data);
        },      

    });     

};

function populateSearch(data)
{
    $('#search_aj').html(data);
}
+1

jQuery.ajaxSetup(), , .

.. ajax , .

( e.state == null ) . .

+1
source

Source: https://habr.com/ru/post/1615241/


All Articles