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: "..." }
.
相关文章