Is it possible to fire multiple ajax requests asynchronously in Magento 2 backend?

久未见 提交于 2019-12-24 10:59:55

问题


What the title says. Im trying to run an import script with AJAX "call 1" and I want to keep track of the import (for feedback purposes) with AJAX "call 2". To give the end user live feedback these calls need to run simultaneously and "call 2" needs to call itself (recursive) to poll for changes.

I have the Controllers and the calls and everything works just fine, just not at the SAME time. Is it a soft lock on the database or is it something else?

Btw I am aware of the "async: true" setting for the ajax call.

[edit] It looks like Magento is preventing me from executing two controllers at the same time. Can anyone confirm this?


回答1:


I think you cannot do two AJAX requests concurrently. This means you always needs to have a logical order, a.k. first 'call 1', then 'call 2'. If you want to make sure call 2 always fires after the call 1 just put it in the success method.

Like so:

$.ajax({
  url: "test-to-call-1",
  context: call-1-context
}).done(function() {
  $.ajax({
    url: "test-to-call-2",
    context: call-2-context
  }).done(function() {
    Now both ajax requests are done.
    And you could add the context of the first one to the second call.
  });



});

If you want to enable polling, just place a setTimeOut loop in which you do the second AJAX call :)

Like this:

function start_polling(counter){
  if(counter < 10){  // poll maximum of 10 times.
    setTimeout(function(){
      counter++;


     $.ajax({
            url: "test-to-call-2",
            context: call-2-context
          }).done(function() {
           start_polling(counter);
            Now both ajax requests are done. 
            And you could add the context of the first one to the second call.
          }).error(function(){
           start_polling(counter);
          });




    }, 1000);
  }
}
$.ajax({
  url: "test-to-call-1",
  context: call-1-context
}).done(function() {

  start_polling(0)



});



回答2:


Well I figured it out.

All I had to do was set:

session_write_close();

In front of the method that started the import and I could start polling with a second AJAX call!

This is probably frowned upon, but it works



来源:https://stackoverflow.com/questions/42274778/is-it-possible-to-fire-multiple-ajax-requests-asynchronously-in-magento-2-backen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!