简体   繁体   中英

javascript & jQuery scope question

I have the following method:

    function priceRange(FESTIVALID){
                      jQuery.ajax({
                            url     : '/actions/festheads.cfc?method=getPriceRangeByGUID',
                            type    : 'POST',
                            data    : 'FESTIVALID='+FESTIVALID,
                            dataType: 'json',
                            success : function(data) {
                                console.info("AJAX:qPrices",data.MINPRICE);

                                    formatedPriceRange = '$ '+data.MINPRICE;
                                    console.info("AJAX:formatedPriceRange", formatedPriceRange);

                                }//success
                            });//ajax;


                    //
                    return formatedPriceRange;
                };

The second console.info correctly displays the formatedPriceRange, but outside the function is undefined.

how can I access this variable out side the priceRange function? Thanks

It's normal, that's how AJAX works. It's asynchronous, meaning that the jQuery.ajax function returns immediately and in this case formatedPriceRange hasn't yet been assigned a value and once the server responds (which can be for example 10 seconds later), the success callback is invoked and the variable is assigned a value.

So always consume the results of your AJAX requests inside the success callback function.

You also have the possibility to pass the async: false option to your jQuery.ajax call which will perform a synchronous request to the server and block until the result is retrieved. Obviously this will lead to your browser freezing during the execution of the request. So it would no longer be AJAX (Asynchronous Javascript And Xml) but SJAX (Synchronous Javascript and Xml).

how can I access this variable out side the priceRange function?

Like Darin said, you have to use your results in the success callback function.

Assuming you're using your current function like this:

    var range = priceRange(festivalId);
    // ... doing stuff with range variable

You'll want reorganize your code so that anything you do with the range variable stems from the success callback. For example, you can create a function to handle updating the UI with the new range:

function handleRangeVariabe(range) {
    /// ... do stuff with range variable
}

Call it from success :

success: function(data) {
    console.info("AJAX:qPrices",data.MINPRICE);
    formatedPriceRange = '$ '+data.MINPRICE;
    console.info("AJAX:formatedPriceRange", formatedPriceRange);

    handleRangeVariable(formatedPriceRange);
}
  1. You have to make sure that the AJAX request finishes before you access the price range data.
  2. You need to expose the price range data outside the scope of the success function.

Here's how you can do it:

function priceRange(FESTIVALID, callback) {
    jQuery.ajax({
        url: '/actions/festheads.cfc?method=getPriceRangeByGUID',
        type: 'POST',
        data: 'FESTIVALID=' + FESTIVALID,
        dataType: 'json',
        success: function(data) {
            console.info("AJAX:qPrices", data.MINPRICE);
            formatedPriceRange = '$ ' + data.MINPRICE;
            console.info("AJAX:formatedPriceRange", formatedPriceRange);
            callback.call(this, formatedPriceRange);
        } //success
    }); //ajax;
}

var myFestivalID = 1;
priceRange(myFestivalID, function(priceRange) {
    // this code runs when the ajax call is complete
    alert('The formatted price range is:' + priceRange);
});

Flower the steps of sample Code:

     //declare function
 function priceRange(FESTIVALID, functionCallBack){
    //1º step
    jQuery.ajax({
        url     : '/actions/festheads.cfc?method=getPriceRangeByGUID',
        type    : 'POST',
        data    : 'FESTIVALID='+FESTIVALID,
        dataType: 'json',
        success : function(data) {

            //3º step, because this function will only trigger when server responds to request
            //handle data in other function
            functionCallBack(data);

            }//success
        });//ajax;

    //more code
    //2º step

    //no return value, because this method no know when the data will return of server 
    //return formatedPriceRange;
};

var formatedPriceRange;
//using function
princeRange(1 , function(data){
    console.info("AJAX:qPrices",data.MINPRICE);
    formatedPriceRange = '$ '+data.MINPRICE;
    console.info("AJAX:formatedPriceRange", formatedPriceRange);
});

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