Ajax jquery 异步返回值 [英] Ajax jquery async return value

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

问题描述

如何使此代码返回值而不冻结浏览器.
你当然可以用新的方法重写它.

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

我需要在其他时间从 php 文件中获取至少 20 个变量.

推荐答案

这是不可能的.
Javascript 在 UI 线程上运行;如果您的代码等待服务器回复,则浏览器必须保持冻结状态.

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.

您应该修改您的设计,以便您可以在单个 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: "..." }.

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

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