js for循環裏面套ajax

這裏要明白
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);
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章