阿贾克斯jQuery的异步返回值 [英] Ajax jquery async return value

查看:114
本文介绍了阿贾克斯jQuery的异步返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让这个code返回值不结冰的浏览器
你可以用新课程的方法改写这一点。

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');

编辑: 我需要至少有20个变量来自PHP文件得到在其他时间

推荐答案

这是不可能的。
的Javascript运行在UI线程上;如果服务器的code等待回复,浏览器必须保持冻结。

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) { ... });

请注意,这两个回调将在联合国predictable顺序运行。

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

您应该修改您的设计,让您可以在一个AJAX请求全部二十值。
例如,你可以把一个逗号分隔值列表,并返回一个JSON对象,如 {X:......,Y:...}

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

这篇关于阿贾克斯jQuery的异步返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆