【问题标题】:if statement in Ajax callbackAjax 回调中的 if 语句
【发布时间】:2015-07-05 12:32:27
【问题描述】:

嗨,当使用 ajax 在 php 中满足条件时,我在刷新页面时遇到问题,如果 php 脚本成功,我希望它重新加载页面,但如果不是,那么我只想回显错误。

以下是我的 PHP 代码中返回“成功”或错误消息的部分:

if ($login) {
    echo "success";
} else {
    echo '<p>Username and Password does not match</p>';
};

这是有效的,因为我已经单独对其进行了测试,即使 ajax 用户也可以登录

我认为问题在于使用 if 语句的 ajax 回调。 这是运行 ajax 回调的我的 js 脚本。

$('form.ajax').on('submit', function(){

    var that = $(this),
        url = that.attr('action'),
        type = that.attr('method'),
        data = {};

    that.find('[name]').each(function(index, value){
        var that = $(this),
            name = that.attr('name'),
            value = that.val();

        data[name] = value;
    });

    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(response){
            if(response == "success") {
                                //location.reload();
                window.location = "index.php";
            } else {
                $('#loginError').html(response);
            };
        }
    });

    return false;
});

我已经尝试了网络上的所有内容,但每次 PHP 脚本成功时,它只是回显成功一词,而不是重定向页面或重新加载

【问题讨论】:

  • 您的回复中可能有前导或尾随空格字符。
  • if 之前尝试console.log(response);。看看实际值是多少。可能有新的线路。这是类似线程的答案。 stackoverflow.com/questions/31197638/…
  • 哇!!感谢 Felix,尤其是 chris85,你的建议就像一个魅力

标签: javascript php jquery ajax login


【解决方案1】:

感谢 chris85 提供的完美建议就像黄金一样工作并且能够解决问题,那就是我的 PHP 脚本顶部有一行额外的行,我在使用 console.log(response) 时看到了它,还阅读了您链接的帖子,它将帮助我解决未来的此类问题,再次感谢。

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2015-07-28
    • 2019-05-09
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2020-07-30
    • 2013-04-05
    • 2018-04-18
    相关资源
    最近更新 更多