简体   繁体   中英

Use data from AJAX request outside success function

I'm using beautiful soup to scrape a webpage for some information. I have a user typing in their zip code when reaching the main page of my site and am sending an AJAX request to Django to get some data based off the user input. The code in javascript looks like this:

$(document).ready(function(){
    $('#search').on('click', function(){
        zip = $('#zip').val();
        data = {
            zip: zip
        }
        $.post('/search', data, function(response){
            places = response
            // some Mustache code to render different elements
        });
    });

    $('body').on('click', '.show-place', function(){
        place_id = Number($(this).attr('id'));
        place = places[place_id];
}

Is this the best way to do it? When I set places = response in the success function, I've read that using global variables is sort of frowned upon. I don't know another way to use the response data though. Is there a better way to do this? Thanks.

No, that is not a good way of passing data between functions. Globals never are.

You should encapsulate the logic in some object/function and pass the values to it. In this example, you should:

     // I would suggest wrapping the $.post
    $.post('/search', data, function(response){
        renderElements(response);
    });

An even better way (but a lot harder) would be to build a Renderer element and do something like:

       var renderer = new Renderer(response);
       renderer.render();

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