Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

Ajax jquery async return value

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_char_val(merk)
{  
    var returnValue = null;
    $.ajax({   
                type:       "POST",
                async:      false,   
                url:            "char_info2.php",   
                data:   { name: merk },   
                dataType: "html",  
                success:    function(data)
                                    {
                                        returnValue = data;
                                    } 
        }); 
    return returnValue;
}
var px= get_char_val('x');
var py= get_char_val('y');

EDIT: i need to have at least 20 variables get from php file at other times.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: "..." }.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...