繁体   English   中英

jQuery AJAX和PHP返回true / false

[英]jQuery AJAX and PHP return true/false

我想知道如何使用jQuery AJAX从PHP脚本检索return true或false。 这是我当前的ajax调用代码,即使登录实际上没有成功,它也总是可以直接转到输入用户名的个人资料页面。

    $("#signInForm").submit(function() {
        $(document).ajaxStart(function() {
            $("#loading" ).show();
        });
        $.ajax({
            url: "/ajax/signIn.php", // Action of the form
            data: $("#signInForm").serialize(), // Send forms data to server
            dataType: "JSON", // Take response as JSON
            type : "POST", // Send form by post or get
            complete: function(result) {
                $(document).ajaxStop(function() {
                    $("#loading" ).hide();
                });
                $("#ajaxResponse").html(result.responseText);
                $("#ajaxResponse").slideDown("slow");
                var username = $("#usernameSignIn").val();
                setTimeout(function() {
                    window.location.href = "/profile.php?username=" + username;
                }, 3000);
            }
        });
        return false;  // Default submit return false
    });

呼叫complete触发complete触发---不考虑结果-我想只要response -完全可以接受。

否则,您可能想使用success ,但是在这种情况下,您需要做的就是根据该response确定要做什么

即:

if(response === true){ //proceed }else{ alert("error!"); }

您必须自己输入逻辑-因为completesuccess仅与数据的实际传输有关,而与数据的内容无关。

因此,在您的代码中:

$("#signInForm").submit(function() {
    $(document).ajaxStart(function() {
        $("#loading" ).show();
    });
    $.ajax({
        url: "/ajax/signIn.php", // Action of the form
        data: $("#signInForm").serialize(), // Send forms data to server
            dataType: "JSON", // Take response as JSON
            type : "POST", // Send form by post or get
            complete: function(result) {
                $(document).ajaxStop(function() {
                    $("#loading" ).hide();
                });
                $("#ajaxResponse").html(result.responseText);
                $("#ajaxResponse").slideDown("slow");
if(result.success === true){
                var username = $("#usernameSignIn").val();
                setTimeout(function() {
                    window.location.href = "/profile.php?username=" + username;
                }, 3000);} 
else { //the result.responseText is probably suitable here, eh? so you could just:
$("#ajaxResponse").slideUp(5000); }
            }
        });
        return false;  // Default submit return false
    });

暂无
暂无

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

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