首页 > 解决方案 > 使用 commandButton click in loop 多次触发 ajax 调用

问题描述

我在 javascript 循环中多次通过隐藏的命令按钮触发 ajax 调用时遇到问题。实际上,javascript 代码似乎在 ajax 调用获得成功响应之前执行,因此,我每次处理的值不会在发送 ajax 下一个请求之前更新。

下面我展示一个例子

.xhtml 表单代码

<h:form id = "jsfform">
  <h:inputHidden id="attributes" value="#{myBean.attributesStr}" />
  <p:commandButton id="button" update="@form" style="display: none"
      ajax="true">
     <f:actionListener binding="#{myBean.bindAttributes()}"/>
  </p:commandButton>
</h:form>

MyBean.java

@ManagedBean(name = "myBean")
@ViewScoped
public class MyBeanimplements Serializable {
   private String attributesStr;
   private List<String> attributes;
   //getters setters ommitted

   public void bindAttributes(){
      this.attributes.add(attributesStr);
   }
}

.js 函数触发按钮进行 ajax 调用

var attributes ="";
function ajaxFunction(){
  for(let index = 0; index < 5; index++){
    attributes += "a";
    document.getElementById('jsfform:attributes').value = attributes
    document.getElementById('jsfform:button').onclick(); //trigger the ajax function
  }
}

当我现在调试时,我的列表似乎有以下值

["a","a","a","a","a"]

虽然我希望我的价值观是

["a","aa","aaa","aaaa","aaaaa"]

这是由于我通过隐藏输入字段从表单绑定到后端变量的值没有按时更新,因为 javascript 代码在第一个请求返回其响应之前按顺序执行 ajax 请求

在这些情况下有哪些解决方法?提前致谢 :)

我试过的

我试图在单击按钮时“禁用”按钮,并在我的 AJAX 调用的完成事件中“重新启用”它,并让 javascript 等待我的按钮重新启用,但这导致了无限循环。

<h:form id = "jsfform">
  <h:inputHidden id="attributes" value="#{myBean.attributesStr}" />
  <p:commandButton id="button" update="@form" style="display: none"
      ajax="true" oncomplete="this.disabled = false">
     <f:actionListener binding="#{myBean.bindAttributes()}"/>
  </p:commandButton>
</h:form>

并在 javascript 中等待按钮重新启用

var attributes ="";
function ajaxFunction(){
  for(let index = 0; index < 5; index++){
    attributes += "a";
    while(true) {
      if(document.getElementById('jsfform:button').disabled == false){
         document.getElementById('jsfform:attributes').value = attributes
         document.getElementById('jsfform:button').onclick(); //trigger the ajax function
         document.getElementById('jsfform:button').disabled = true;
         break;
      }
    }

  }
}

标签: jsfcommandbutton

解决方案


推荐阅读