如何使 JQuery-AJAX 请求同步

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13971769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:08:52  来源:igfitidea点击:

How to make JQuery-AJAX request synchronous

jqueryajaxsynchronous

提问by Kanishk Dudeja

How do i make an ajax request synchronous?

我如何使 ajax 请求同步?

I have a form which needs to be submitted. But it needs to be submitted only when the user enters the correct password.

我有一个表格需要提交。但是只有当用户输入正确的密码时才需要提交。

Here is the form code:

这是表单代码:

<form name="form" action="insert.php" method="post" onSubmit="return ajaxSubmit(this);" >

And the jquery code for sending and checking password is this:

用于发送和检查密码的jquery代码是这样的:

var ajaxSubmit = function(formE1) {

    var password = $.trim($('#employee_password').val());

    $.ajax({
        type: "POST",
        async: "false",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            if(arr == "Successful") {
                return true;
            } else {
                return false;
            }
        }
    });
}

However the form always submits, regardless of the value returned by the ajax request. I have checked everything else. The value of arr is coming out to be 'successful' when correct password is entered and works correctly vice versa too.

但是,无论 ajax 请求返回的值如何,表单总是会提交。我已经检查了其他一切。当输入正确的密码时, arr 的值显示为“成功”,反之亦然。

How do i make this request synchronous? as far as i can debug, the request is asynchronous so the form gets submitted before the request gets completed.

我如何使这个请求同步?就我可以调试而言,请求是异步的,因此在请求完成之前提交表单。

Code for checkpass.php

checkpass.php 的代码

<?php 
require("includes/apptop.php");
require("classes/class_employee.php");
require("classes/class_employee_attendance.php");

$employee_password=$_POST['password']; 

$m=new employee();
$m->setbyid_employee(1);
$arr=$m->editdisplay_employee();

if($arr['employee_password'] == $employee_password)
{
$res="Successful";  
}
else
{
$res="Password not match";  
}

echo $res;
?>

Update: The solution has been found.

更新:已找到解决方案。

As pointed by Olaf Dietshche: The return value of ajaxSubmitis not the return value of the success: function(){...}. ajaxSubmitreturns no value at all, which is equivalent to undefined, which in turn evaluates to true.

正如 Olaf Dietshche 所指出的: 的返回值ajaxSubmit不是success: function(){...}. ajaxSubmit根本不返回任何值,这相当于undefined,而后者的计算结果为true

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

这就是为什么表单总是被提交并且与是否同步发送请求无关的原因。

So, I set a variable to 1inside success function upon successful. And checked its value out of success function, if it was 1outside the success function, then I wrote return true ... else return false. And that worked.

因此,我1在成功后将变量设置为成功函数内部。并从成功函数中检查它的值,如果它1在成功函数之外,那么我写了return true ... else return false. 那奏效了。

Updated working code:

更新的工作代码:

var ajaxsubmit=function(forme1) {
    var password = $.trim($('#employee_password').val());
    var test="0";

    $.ajax({
        type: "POST",
        url: "checkpass.php",
        async: false,
        data: "password="+password,
        success: function(html) {
            if(html == "Successful") {
                test="1";
            } else {
                alert("Password incorrect. Please enter correct password.");
                test="0";
            }
        }
    });

    if(test=="1") {
        return true;
    } else if(test=="0") {
        return false;
    }
}

回答by Olaf Dietsche

From jQuery.ajax()

来自jQuery.ajax()

asyncBoolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

asyncBoolean
默认值:true
默认情况下,所有请求都是异步发送的(即默认设置为 true)。如果您需要同步请求,请将此选项设置为 false。

So in your request, you must do async: falseinstead of async: "false".

所以在你的请求中,你必须做async: false而不是async: "false".

Update:

更新

The return value of ajaxSubmitis notthe return value of the success: function(){...}. ajaxSubmitreturns no value at all, which is equivalent to undefined, which in turn evaluates to true.

的返回值ajaxSubmit不是的返回值success: function(){...}ajaxSubmit根本不返回任何值,这相当于undefined,而后者的计算结果为真。

And thatis the reason, why the form is always submitted and is independent of sending the request synchronous or not.

也是这个道理,为什么表单总是提交并独立发送请求同步与否。

If you want to submit the form only, when the response is "Successful", you must return falsefrom ajaxSubmitand then submit the form in the successfunction, as @halilb already suggested.

如果您只想提交表单,当响应为 时"Successful",您必须返回falsefromajaxSubmit然后在success函数中提交表单,正如@halilb 已经建议的那样。

Something along these lines should work

沿着这些路线的东西应该工作

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

回答by Kaszoni Ferencz

It's as simple as the one below, and works like a charm.

它和下面的一样简单,就像一个魅力。

My solution perfectly answers your question: How to make JQuery-AJAX request synchronous

我的解决方案完美地回答了您的问题:How to make JQuery-AJAX request synchronous

Set ajax to synchronous before the ajax call, and then reset it after your ajax call:

在 ajax 调用之前将 ajax 设置为同步,然后在 ajax 调用之后重置它:

$.ajaxSetup({async: false});

$ajax({ajax call....});

$.ajaxSetup({async: true});

In your case it would look like this:

在您的情况下,它看起来像这样:

$.ajaxSetup({async: false});

$.ajax({
        type: "POST",
        async: "false",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            if(arr == "Successful") {
                return true;
            } else {
                return false;
            }
        }
    });


$.ajaxSetup({async: true});

I hope it helps :)

我希望它有帮助:)

回答by halilb

Instead of adding onSubmit event, you can prevent the default action for submit button.

您可以阻止提交按钮的默认操作,而不是添加 onSubmit 事件。

So, in the following html:

因此,在以下 html 中:

<form name="form" action="insert.php" method="post">
    <input type='submit' />
</form>?

first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

首先,防止提交按钮动作。然后异步进行ajax调用,密码正确后提交表单。

$('input[type=submit]').click(function(e) {
    e.preventDefault(); //prevent form submit when button is clicked

    var password = $.trim($('#employee_password').val());

     $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(html) {
            var arr=$.parseJSON(html);
            var $form = $('form');
            if(arr == "Successful")
            {    
                $form.submit(); //submit the form if the password is correct
            }
        }
    });
});????????????????????????????????

回答by bipen

I added dataType as json and made the response as json:

我将 dataType 添加为 json 并将响应设为 json:

PHP

PHP

echo json_encode(array('success'=>$res)); //send the response as json **use this instead of echo $res in your php file**

JavaScript

JavaScript

  var ajaxSubmit = function(formE1) {

        var password = $.trim($('#employee_password').val());    
        $.ajax({
            type: "POST",
            async: "false",
            url: "checkpass.php",
            data: "password="+password,
            dataType:'json',  //added this so the response is in json
            success: function(result) {
                var arr=result.success;
                if(arr == "Successful")
                {    return true;
                }
                else
                {    return false;
                }
            }
        });

  return false
}

回答by silly

try this

尝试这个

the solution is, work with callbacks like this

解决方案是,使用这样的回调

$(function() {

    var jForm = $('form[name=form]');
    var jPWField = $('#employee_password');

    function getCheckedState() {
        return jForm.data('checked_state');
    };

    function setChecked(s) {
        jForm.data('checked_state', s);
    };


    jPWField.change(function() {
        //reset checked thing
        setChecked(null);
    }).trigger('change');

    jForm.submit(function(){
        switch(getCheckedState()) {
            case 'valid':
                return true;
            case 'invalid':
                //invalid, don submit
                return false;
            default:
                //make your check
                var password = $.trim(jPWField.val());

                $.ajax({
                    type: "POST",
                    async: "false",
                    url: "checkpass.php",
                    data: {
                        "password": $.trim(jPWField.val);
                    }
                    success: function(html) {
                        var arr=$.parseJSON(html);
                        setChecked(arr == "Successful" ? 'valid': 'invalid');
                        //submit again
                        jForm.submit();
                    }
                    });
                return false;
        }

    });
 });

回答by mymotherland

Can you try this,

你可以试试这个吗

var ajaxSubmit = function(formE1) {

            var password = $.trim($('#employee_password').val());

             $.ajax({
                type: "POST",
                async: "false",
                url: "checkpass.php",
                data: "password="+password,
                success: function(html) {
                    var arr=$.parseJSON(html);
                    if(arr == "Successful")
                    { 
                         **$("form[name='form']").submit();**
                        return true;
                    }
                    else
                    {    return false;
                    }
                }
            });
              **return false;**
        }

回答by rudresh solanki

The below is a working example. Add async:false.

下面是一个工作示例。添加async:false.

const response = $.ajax({
                    type:"POST",
                    dataType:"json",
                    async:false, 
                    url:"your-url",
                    data:{"data":"data"}                        
                });                   
 console.log("response: ", response);