jQuery.ajax()中的“异步:假”是做什么的?


256

具体来说,它与默认设置(async: true)有何不同?

在什么情况下我想显式设置asyncfalse,它与防止页面上的其他事件触发有关系吗?



是的,在我看来,如果它不是异步的,则应将其称为“ Ajax”(异步JavaScript和XML)以外的东西……
devlord 2012年

异步意味着脚本将向服务器发送请求,并继续执行它,而无需等待答复。收到回复后,立即触发浏览器事件,该事件又允许脚本执行关联的操作。
SagarPPanchal 2014年

Answers:


300

它与阻止页面上的其他事件触发有关系吗?

是。

将async设置为false意味着要调用的语句必须先完成,然后才能调用函数中的下一条语句。如果您设置async:true,则该语句将开始执行,无论async语句是否已完成,都将调用下一条语句。

有关更多信息,请参见: jQuery ajax成功匿名函数作用域


12
我一直想知道这是如何实现的,因为JavaScript不是线程化的。
马特

4
@ L.DeLeo-不,一点也不-延迟是管理异步函数调用复杂性的另一种方法-完全async: false 消除了调用的异步性ajax 调用-直到服务器响应后,才会执行其后的代码。
肖恩·维埃拉

14
请记住,这也意味着浏览器将不会捕获/触发执行ajax时发生的任何事件。我发现这很困难,试图找出为什么Firefox没有触发点击事件的原因。原来是由于“强制”模糊事件,随后的同步调用阻止了该事件。
PålOliver

3
@Matt不,它不是(不再^^)w3schools.com/html/html5_webworkers.asp
borrel

5
似乎async: false已经死了,我尝试了一下,就得到了18:17:49.384 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/ 1 jquery.js:9061:4
阿巴(Aba)

120
  • async:false=代码已暂停。(其他代码等待完成。)
  • async:true=代码继续。(什么都没有暂停。其他代码不在等待中。)

就这么简单。


相当通用的“其余代码”,解释了被暂停的代码范围。
巴特

26

Async:False将保留其余代码的执行。一旦获得ajax的响应,只有这样,其余代码才会执行​​。


18

如果禁用异步检索,则脚本将阻塞,直到满足请求为止。尽管我发现异步回调更为简洁,但它对于按已知顺序执行请求序列很有用。


乔:这将取决于您在后台是否有任何工作线程。
约翰·

10

一种用例是ajax在用户关闭窗口或离开页面之前进行呼叫。这就像在用户可以导航到另一个站点或关闭浏览器之前删除数据库中的一些临时记录。

 $(window).unload(
        function(){
            $.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}
        });
    });

51
没有任何JavaScript会阻止浏览器窗口关闭
jammykam 2014年

对于完全不相关的内容,我需要async false,但它解决了我的问题,因为它允许我的脚本从xml文件中获取值,然后将其填充为未定义的页面。
J_L

8

https://xhr.spec.whatwg.org/#synchronous-flag

工作人员外部的同步XMLHttpRequest正在从Web平台中删除,因为它会对最终用户的体验产生不利影响。(这是一个耗时多年的漫长过程。)当JavaScript全局环境是文档环境时,开发人员不得为async参数传递false。强烈建议用户代理警告开发人员工具中的此类用法,并可以尝试在发生InvalidAccessError异常时抛出该异常。未来的方向是只允许在工作线程中使用XMLHttpRequests。该消息旨在作为对此的警告。


8

将async设置为false意味着ajax请求之后的指令将必须等待请求完成。在以下情况下,必须将async设置为false才能使代码正常工作。

var phpData = (function get_php_data() {
  var php_data;
  $.ajax({
    url: "http://somesite/v1/api/get_php_data",
    async: false, 
    //very important: else php_data will be returned even before we get Json from the url
    dataType: 'json',
    success: function (json) {
      php_data = json;
    }
  });
  return php_data;
})();

上面的示例清楚地说明了async:false的用法

通过将其设置为false,我们确保一旦从url中检索到数据,仅在返回php_data之后;叫做


以防万一其他人遇到与我相同的问题:此答案强调该return php_data语句不能在成功函数中,而必须在$.ajax()函数外部。我把等价的东西放到了return php_data里面,success: function(){}并且总是返回未定义的
gordon613 '19

0

使用此选项小数:3

这是网址:https : //demos.telerik.com/kendo-ui/numerictextbox/index

<!DOCTYPE html>
<html>
<head>
    <base href="https://demos.telerik.com/kendo-ui/numerictextbox/index">
    <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
    <title></title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default-v2.min.css" />

    <script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jquery.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script>


</head>
<body>

        <div id="example">
            <div id="add-product" class="demo-section k-content">
                <p class="title">Add new product</p>
                <ul id="fieldlist">
                    <li>
                        <label>
                            Price:
                            <input id="currency" type="number" title="currency" value="30" min="0" max="100" style="width: 100%;" />
                        </label>
                    </li>
                    <li>
                        <label>
                            Price Discount:
                            <input id="percentage" value="0.05" title="percentage" style="width: 100%;" />
                        </label>
                    </li>
                    <li>
                        <label>
                            Weight:
                            <input id="custom" value="2" title="custom" style="width: 100%;" />
                        </label>
                    </li>
                    <li>
                        <label>
                            Currently in stock:
                            <input id="numeric" type="number" title="numeric" value="17" min="0" max="100" step="1" style="width: 100%;" />
                        </label>
                    </li>
                </ul>
            </div>


            <script>
                $(document).ready(function() {
                    // create NumericTextBox from input HTML element
                    $("#numeric").kendoNumericTextBox();

                    // create Curerncy NumericTextBox from input HTML element
                    $("#currency").kendoNumericTextBox({
                        format: "c",
                        decimals: 3
                    });

                    // create Percentage NumericTextBox from input HTML element
                    $("#percentage").kendoNumericTextBox({
                        format: "p0",
                        min: 0,
                        max: 0.1,
                        step: 0.01
                    });

                    // create NumericTextBox from input HTML element using custom format
                    $("#custom").kendoNumericTextBox({
                        format: "#.00 kg"
                    });
                });
            </script>

            <style>
                .demo-section {
                    padding: 0;
                }

                #add-product .title {
                    font-size: 16px;
                    color: #fff;
                    background-color: #1e88e5;
                    padding: 20px 30px;
                    margin: 0;
               }

               #fieldlist {
                   margin: 0 0 -1.5em;
                   padding: 30px;
               }

               #fieldlist li {
                   list-style: none;
                   padding-bottom: 1.5em;
               }

               #fieldlist label {
                   display: block;
                   padding-bottom: .6em;
                   font-weight: bold;
                   text-transform: uppercase;
                   font-size: 12px;
               }

               #fieldlist label .k-numerictextbox {
                   font-size: 14px;
               }
            </style>

        </div>


</body>
</html>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.