Ajax jquery async return value(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异步返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Ajax jquery异步返回值


- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01