Ajax jquery async return value

前端 未结 3 1119
予麋鹿
予麋鹿 2020-11-30 14:10

how can i make this code to return the value without freezing the browser.
You can rewrite this with new method of course.

function get_         


        
相关标签:
3条回答
  • 2020-11-30 14:38

    You can not make variable assignments this way (async). you must set the variables in the success handler.

    variableArray = new Array(); 
    
    get_char_val('x');
    get_char_val('y');
    
    function get_char_val(merk)
    {  
        var returnValue = null;
        $.ajax({   
            type:       "POST",
            url:            "char_info2.php",   
            data:   { name: merk },   
            dataType: "html",  
            success:    function(data)
                {
                    variableArray[merk] = data;
                } 
        }); 
    }
    

    Once all of the retrievals are finished you can access the x and y variables by using variableArray[x] and variableArray[y]

    0 讨论(0)
  • 2020-11-30 14:40

    This is not possible.
    Javascript runs on the UI thread; if your code waits for the server to reply, the browser must remain frozen.

    Instead, you need to return the value using a callback:

    function get_char_val(merk, callback)
    {  
        var returnValue = null;
        $.ajax({   
                    type:       "POST",
                    url:            "char_info2.php",   
                    data:   { name: merk },   
                    dataType: "html",  
                    success:    function(data) {
                        callback(data);
                    } 
            }); 
    }
    
    get_char_val('x', function(px) { ... });
    get_char_val('y', function(py) { ... });
    

    Note that the two callbacks will run in an unpredictable order.


    You should modify your design so that you can get all twenty values in a single AJAX request.
    For example, you can take a comma-separated list of values, and return a JSON object like { x: "...", y: "..." }.

    0 讨论(0)
  • 2020-11-30 15:02

    This may not be what you are expecting but you can set async: true if you dont want pause in the browser and so what you want to do with px on success

    0 讨论(0)
提交回复
热议问题