简体   繁体   中英

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. The case is I want to send a post request when the base64 field is not empty anymore. I can't use setTimeout function because the encoding time is dynamic depends on the file size.

 $(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 没有时间执行回调。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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