synchronous fetch to replace synchronous ajax

时间:2018-03-23 00:20:42

标签: javascript ajax fetch synchronous

I understand that making synchronous calls are not recommended, but I have to make a synchronous call in ajax, since I am dealing with a device which requires user action before I get the response from it. My ajax() code below has been working great until now. I am getting the warning that "Synchronous XMLHttpRequest on the main thread is deprecated". Synchronous call returns the response (from the device) and I pass it to my second call and output gets generated:

<script>		
var result = $.ajax({
    url: 'url',
	async: false,
	type: "GET"
}).responseText;

$(document).ready(function() {   
    $.post("https://example.com/doit.php", {
        response: result,account: <?php echo $account ?>,dn:<?php echo $dn ?>, mode:<?php echo $dest ?>},function(data){document.write(data);});
    });
</script>

How can I change the synchronous call to keep this working.

2 个答案:

答案 0 :(得分:1)

Try this

<script>
    $(document).ready(function(){   
        $.ajax({
          url: 'url',
          type: "GET",
          success: function(r){
             var result = r.responseText;
             $.post("https://example.com/doit.php",{response: result,account: <?php echo $account ?>,dn:<?php echo $dn ?>, mode:<?php echo $dest ?>},function(data){document.write(data);});
          }
        });
    });
</script>

答案 1 :(得分:0)

Do your post request in the success callback of your get:

$.ajax({
    url: 'url',
    type: "GET"
})
    .then(function(responseText) {
        return $.post(...)
    })
    .then(function(postResponse) {
        ..do whatever
    })