简体   繁体   中英

Retrieving a javascript variable created in an onchange javascript event

I have the following simple form from which a user can select a state to view information on:

<form style="position:absolute; top:65px; left:650px">
    Select State to View:
    <select id="myList" onchange="load_state_data(); xml = getStateInfo();">
      <option selected="selected"></option>
        <?php
            foreach($stateNames as $state){
                echo('<option>'.$state.'</option>');
            }
        ?>
    </select>
</form>

My javascript is as follows:

function load_state_data() {
    var state_name = $("#myList option:selected").val();
    $.ajax({
        type: 'post',
        url: 'state_data.php',
        dataType: "xml",
        data: {
            state_name: $("#myList option:selected").val()
        },
        success: function (data) {
            //clear out previous values
            for (j = 0; j < 5; j++) {
                $('#top_name_' + j).html("");
                $('#top_score_' + j).html("");
            }

            $(data).find('TOP').each(function (index) {
                $('#top_name_' + index).html($(this).find('COMPANY_NAME').text());
                $('#top_score_' + index).html($(this).find('Q_SCORE').text());
            });

            //initialize my temp arrays for reverse ordering the results
            var botName = new Array();
            var botScore = new Array()

            //clear out previous values
            for (j = 0; j < 5; j++) {
                $('#bot_name_' + j).html("");
                $('#bot_score_' + j).html("");
            }

            $(data).find('BOTTOM').each(function (index) {
                //$('#bot_name_'+index).html($(this).find('COMPANY_NAME').text());
                //$('#bot_score_'+index).html($(this).find('Q_SCORE').text());
                botName[index] = $(this).find("COMPANY_NAME").text();
                botScore[index] = $(this).find("Q_SCORE").text();
                j = index;
            });
            var newOrderName = botName.reverse();
            var newOrderScore = botScore.reverse();
            for (i = 0; i < newOrderName.length; i++) {
                $('#bot_name_' + i).html(newOrderName[i]);
                $('#bot_score_' + i).html(newOrderScore[i]);
            }

            //clear the variables from memory
            delete botName;
            delete botScore;
            delete newOrderName;
            delete newOrderScore;


            //cycle through results and save my locations to an array of the map markers
            var inst_info = new Array();
            $(data).find('INST_MARKER').each(function (index) {
                inst_info[index] = [parseFloat($(this).find('LAT').text()),
                parseFloat($(this).find('LONG').text()),
                $(this).find('COMPANY_NAME').text(), $(this).find('Q_SCORE').text()];
            });

            $(data).find('INST_COUNT').each(function () {
                $('#num_total').html($(this).find('NUM_TOTAL').text());
                $('#num_null').html($(this).find('NUM_NULL').text());
            });
            return (inst_info);
        },
        error: function (data) {
            alert('There was an error. Please try again shortly.');
        }
    });
};

I need to access the inst_info generated in this script back on the page it is called from (see form above). Is this possible, and, if so, how? I have tried using inst_info = function load_state_data, but that doesn't work.

This isn't really possible. The event handler fires asynchronously at some point in time, and there's no code to "return" a value to. Whatever happens in the event handler load_state_data() is isolated from your main javascript code, because nobody knows when, and if at all, it will happen. You have to do whatever it is you want to do right in the event handler.

I need to access the inst_info generated in this script back on the page it is called from (see form above). Is this possible, and, if so, how?

No. The inst_info is created in the callback function for the success event of your asynchronous request. From there it is available, and you will be able to call a function that sets the state information.

All this happens in the future, after your load_state_data function returns. Yet, you might return a Promise for the data, on which other callback functions can be registered to be executed as soon as the data is available.


    //clear the variables from memory
    delete ...

This code does not work, it is a misuse of the delete operator . You don't need to do this anyway, JavaScript is a garbage-collected language.

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