使用 $.ajax 执行同步请求

发布于 2024-10-05 09:04:44 字数 1070 浏览 2 评论 0原文

我们知道只有同步请求是通过 $.ajax 完成的,并带有 async:false 选项 但我在Jquery手册中看到说“同步请求可能会暂时阻塞浏览器” 在请求处于活动状态时禁用任何操作”。我有一些问题,例如

我看到一些答案说使用回调 () 如何让 jQuery 执行同步而不是异步 Ajax 请求?。 我如何将其实现到我的功能中。

在下面的函数中,如果请求失败或响应没有返回,我该如何处理它。我的意思是我可以使用“错误:”或类似的东西吗? 我怎样才能有效地改进这个功能,我的意思是使用回调和错误处理。据说(我们永远不能通过请求进行错误和成功回调)

function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }

we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently i mean using call back and error handling .It is said that (we can never have error and success call back with a request)

function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧伤慢歌 2024-10-12 09:04:44

您的同步请求将导致 UI 线程(以及浏览器)等待,直到 XMLHttpRequest 对象返回(不管它是失败还是成功)。

jQuery 将执行您的成功/完成和错误处理程序,就像您使用“正常”异步请求时执行的方式一样。但在此之前它会等待/阻塞。

因此,最糟糕的情况是,实际请求需要花费大量时间。在这种情况下,网络延迟非常糟糕,数据量很大……所有这些都会完全锁定你的 UI 线程,这显然是一个很棒的用户体验。

我真的不知道现在应该在哪里使用同步ajax请求。

Your synchronized request will cause the UI thread (and therefore the browser) to wait until the XMLHttpRequest object returns (kind regardless whether it failed or succeded).

jQuery will execute your success / complete and error handler the same way it would execute when you're using a "normal" asynchronous request. But it will wait / block before it does so.

So the worst case scenario here would be, that the actual request takes a huge amount of time. Network latencys are pretty bad in this context, large data amounts.. all those will entirely lock up your UI thread which is obviously an aweful user expierence.

I really don't know where someone should use a synchronized ajax request nowadays.

世界和平 2024-10-12 09:04:44

您最好不要使用 async: false,而是执行以下操作:

function begin_ajax() {
    // Set your UI states here
}

function success_ajax(data) {
    // Run whatever needs to run if the request is successful.
}

function error_ajax(xhr, error_type, msg) {
    // Display error messages
}

function complete_ajax() {
    // Clean up UI
}
$.ajax({
    beforeSend: begin_ajax,
    success: success_ajax,
    error: error_ajax,
    complete: complete_ajax
    // Your parameters here
});

Rather than using async: false, you'd be better off doing something like this:

function begin_ajax() {
    // Set your UI states here
}

function success_ajax(data) {
    // Run whatever needs to run if the request is successful.
}

function error_ajax(xhr, error_type, msg) {
    // Display error messages
}

function complete_ajax() {
    // Clean up UI
}
$.ajax({
    beforeSend: begin_ajax,
    success: success_ajax,
    error: error_ajax,
    complete: complete_ajax
    // Your parameters here
});
腹黑女流氓 2024-10-12 09:04:44

“超时”提供理由

使用完整的函数并为 jQuery Docs 中的

完成(XMLHttpRequest,
textStatus) - 函数

一个函数
请求完成时调用
(成功和错误回调之后
执行)。函数被传递了
两个参数: XMLHttpRequest
对象和一个字符串分类
请求的状态(“成功”,
“未修改”、“错误”、“超时”或
“解析器错误”)。这是一个 Ajax 事件。

所以代码在你的ajax上看起来像这样:

function empvalidate() {
      var exists = false;             // default return value is false
      var empno = $("#empno").val();
      if (empno != '') {
        $.ajax({
          url: "emp.php",
          async: false,
          dataType: "json",
          data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
          success: function (data, ts) {
            
              if(ts == "success")
                   exists = data.status; // set status of existence to outer variable
              else if(ts == "timeout")
              {
                   $(document).trigger('customTimeoutHandler');
              }
          }
        });
      }
      return exists;                  // return actual value
    }

不太确定这里的应用程序,但请记住你也可以在这里设置一个自定义超时变量。不太确定你想要它是什么,这仅取决于你的场景。

Use the complete function and make a case for "timeout"

from jQuery Docs

complete(XMLHttpRequest,
textStatus) - Function

A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

so Code would look something like this on your ajax:

function empvalidate() {
      var exists = false;             // default return value is false
      var empno = $("#empno").val();
      if (empno != '') {
        $.ajax({
          url: "emp.php",
          async: false,
          dataType: "json",
          data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
          success: function (data, ts) {
            
              if(ts == "success")
                   exists = data.status; // set status of existence to outer variable
              else if(ts == "timeout")
              {
                   $(document).trigger('customTimeoutHandler');
              }
          }
        });
      }
      return exists;                  // return actual value
    }

Not really sure of the application here, but remember that you can also set a custom timeout variable here too. Not too sure what you would want it to be, it just depends on your scenario.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文