Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery停止异步运行ajax_Javascript_Jquery_Ajax_Asynchronous - Fatal编程技术网

Javascript jQuery停止异步运行ajax

Javascript jQuery停止异步运行ajax,javascript,jquery,ajax,asynchronous,Javascript,Jquery,Ajax,Asynchronous,有没有办法防止ajax异步运行 jQuery: var returnValue = false; var appCount = 0; $.ajax({ type: "GET", url: "getBookedAppointmentCountByDoctorAndDate.php", data: dataString, success: function (respon

有没有办法防止ajax异步运行

jQuery:

var returnValue = false;
        var appCount = 0;

        $.ajax({
            type: "GET",
            url: "getBookedAppointmentCountByDoctorAndDate.php",
            data: dataString,
            success: function (response){
                appCount = response;
                //alert(appCount);
                if(appCount >= 6){

                    returnValue = true;
                }
            }
        });
        return returnValue;
我的代码中有一个if语句,用于检查此函数的返回值。因为Ajax是异步运行的,所以if语句在设置返回值之前继续。对于返回php值的其他方法有什么想法或建议吗

if (blah($(this)) === true) {
                    alert("blah");
                } else { ...

您正在函数中使用此代码段,对吗?既然您有一个
return
语句,我猜是这样的

不能返回将在异步任务中确定的值。您可以做的是将回调函数传递给该函数,当确定值时,将该值传递给该函数并调用它

function myFunc(callback) {

    var returnValue = false;
    var appCount = 0;

    $.ajax({
        type: "GET",
        url: "getBookedAppointmentCountByDoctorAndDate.php",
        data: dataString,
        success: function (response){
            appCount = response;
            //alert(appCount);
            if(appCount >= 6){
                returnValue = true;
            }
            callback(returnValue);
        }
    });
}



myFunc(function (value) {
    console.log(value);
    // do what ever you want with `value`
})

另一种方法是使用
Promise
。如果您想使用jQuery的承诺,这里是向ajax参数添加参数
async:false
,ajax请求时浏览器将处于非活动状态,因此这不是一个好的决定


最好将
if语句
移动到ajax成功函数,或者使用
if语句
生成函数,并在成功函数中调用它。

有一种方法,但真正的答案是,你永远不应该这样做!在您的请求中,您必须执行async:false您永远不应该在浏览器上使用sync方法,因为冻结了主线程。要在ajax调用结束时“返回”一个值,您应该使用回调(或者更高级地,返回承诺)。我认为您的意思是
async:false
请将此标记为正确答案。