这里要明白
for循环是同步的
ajax是异步的
所以for循环里面套ajax,for循环会先跑完再跑异步ajax
只需在ajax加上
async: false,
把异步改成同步
$.ajax({
url:'/esf/BlockAction_selectArea.jspx?path=' + overlays_path[i],
dataType: 'json',
async: false,
success:function(result) {
areaname = result["areaname"];
}
});
后台传json
public void selectArea(){
................
JSONObject json = new JSONObject();
json.put("areaname", block.getAreaname());
this.renderText(json.toString());
}
}
protected void renderText(String text) {
render(text, "text/plain;charset=UTF-8");
}
/**
* 封装response用于json输出
*
* @param text
* @param contentType
*/
protected void render(String text, String contentType) {
try {
getHttpServletResponse().setContentType(contentType);
getHttpServletResponse().getWriter().write(text);
} catch (IOException e) {
System.out.println(e);
}
}
本文探讨了for循环与AJAX在同步和异步执行中的差异,阐述了如何将AJAX调用从异步更改为同步,以确保for循环中每个请求的顺序执行。同时,提供了具体的jQuery代码示例和后端JSON响应处理方式。
778

被折叠的 条评论
为什么被折叠?



