加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax请求中的async:false/true的区别

发布时间:2020-12-16 00:36:00 所属栏目:百科 来源:网络整理
导读:Ajax请求中的async:false/true的区别 官方的解释是: asyncBooleanDefault:true Bydefault,allrequestsaresentasynchronous(e.g.thisissettotruebydefault).Ifyouneedsynchronousrequests,setthisoptiontofalse.Notethatsynchronousrequestsmaytemporarilylo

Ajax请求中的async:false/true的区别

官方的解释是:

asyncBooleanDefault:true

Bydefault,allrequestsaresentasynchronous(e.g.thisissettotruebydefault).Ifyouneedsynchronousrequests,setthisoptiontofalse.Notethatsynchronousrequestsmaytemporarilylockthebrowser,disablinganyactionswhiletherequestisactive.

async.默认是true,即为异步方式,$.Ajax执行后,会继续执行ajax后面的脚本,直到服务器端返回数据后,触发$.Ajax里的success方法,这时候执行的是两个线程。若要将其设置为false,则所有的请求均为同步请求,在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

jsp页面:

functionjudgeSupplierAssessment(){

varresult=false;

varquote_list_id=$("input[name='quote_list_id']").val();

varproduct_id=$("#product_id").val();

varurl="<s:urlvalue='/quote/quoteprice!checkSupplierAssessment.action'/>?

quote_list_id="+quote_list_id+"&product_id="+product_id;

$.ajax({

url:encodeURI(url),//处理中文乱码。

type:"POST",//请求的方式:"POST"或者"GET"

dataType:"json",//数据返回的格式

async:false,

success:function(obj){

varflag=obj['flag'];

if(flag=='1'){

result=true;

}

},

error:errorCallBaxk//请求失败后回调函数

});

returnresult;

alert(result);

}

这个ajax请求为同步请求,在没有返回值之前,alert(result)是不会执行的。

如果async设置为:true,则不会等待ajax请求返回的结果,会直接执行ajax后面的语句。

后台代码:

publicStringcheckSupplierAssessment()throwsIOException{

HttpServletRequestrequest=Struts2Utils.getRequest();

SystemUsersystemUser=getUser(request);

Stringpro_id=request.getParameter("product_id");

Stringquote_list_id=request.getParameter("quote_list_id");

PrintWriterout=Struts2Utils.getResponse().getWriter();

HttpServletResponseresponse=Struts2Utils.getResponse();

Map<String,String>map=newHashMap<String,String>();

Stringflag=orderQuoteService.judgeSupplierAssessment

(pro_id,quote_list_id,systemUser);

map.put("flag",flag);

Gsongson=newGson();

Stringjson=gson.toJson(map);

response.setHeader("Cache-Control","no-cache");

response.setContentType("text/json;charset=utf-8");

out.print(json);

out.flush();

returnnull;

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读