简体   繁体   English

JS - 无限循环但条件已经为假

[英]JS - Infinite while loop but the condition is already false

Please help me debug this code.请帮我调试这段代码。 It hangs up when I used the while loop.当我使用 while 循环时它挂断了。 The case is I want to send a post request when the base64 field is not empty anymore.情况是我想在 base64 字段不再为空时发送 post 请求。 I can't use setTimeout function because the encoding time is dynamic depends on the file size.我不能使用 setTimeout 函数,因为编码时间是动态的,取决于文件大小。

 $(document).on('change','.contract-file', function(){ var textField = $(this).siblings('input:not(.contract-file-encoded)'); var fileName = $(this).val().split("\\\\").pop(); var contractId = $(this).closest('.personal-accordion').find('input[type=hidden].contractId'); var staffId = $('input[name=staffId]').val(); var base64Holder = $(this).siblings('.contract-file-encoded') textField.val( fileName ); // show filename var input = $(this); setTimeout(function(){ var fileUpload = new FileReader; var file = input[0].files[0]; var image = new Image(); setTimeout(function(){ fileUpload.onload = function (e){ return function (e){ base64Holder.attr("value",e.target.result); } }(file); fileUpload.readAsDataURL(file); }); }); while( base64Holder.val().length <= 0 ){ console.log('encoding...'); } var params = { _method: 'put', contract_id: contractId.val(), is_saving_contract_file: 1, attribute: { dummy: 'dummy'}, contract_file: base64Holder.val() }; $.post("/ajax/staffs/"+staffId, params, function(data){ console.log('Ajax return:'); console.log(data); }); });

JavaScript 在底层是同步的,所以你不能做你正在做的事情,因为当进入循环时 js 没有时间执行回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM