jsf - 使用 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;
}
}
}
}
解决方案
推荐阅读
- amazon-web-services - AppSync BatchPutItem 不保存项目
- android - com.google.gson.JsonSyntaxException 即使在 android 中使用 TypeToken 也会出现问题?
- ios - Xcode 找不到任何 iOS 应用程序开发配置文件
- javascript - 如何在 EXPRESS-VALIDATOR 中有条件地返回自定义错误消息
- sql - 重构查询函数中的硬编码值
- jquery - 如何将多个值传递给ajax?
- asp.net - 在字符串数组中正确定位字符串
- ios - 为什么我的屏幕从滚动视图的中心开始?IOS
- javascript - setState() 函数不起作用,我无法更新我的状态。我怎么解决这个问题?
- amazon-elastic-beanstalk - AWS 路由 53 配置为指向 Elastic BeanStalk URL