使用PHP(echo)触发jQuery事件


Triggering a jQuery event using PHP (echo)?

我一直在尝试通过PHP触发效果。基本上,当用户输入无效密码时,我想让提交按钮抖动。要做到这一点,我需要使用PHP,并尝试验证数据库中的用户,如果失败,下面的代码应该会触发jQuery效果。

echo'<script>$(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45);</script>';

我明白为什么这可能不起作用,但我看不到其他方法。

您需要AJAX。客户端通过AJAX询问服务器密码是否正确,然后根据结果摇动按钮(是否正确)。类似这样的东西:

$.ajax("http://www.example.com/ajax.php", {
  data: {
    username: username,
    password: password
  },
  success: function(data) {
    if (data.okay) {
      loggedIn = true;
    } else {
      $(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45);    if (data == "OK");
    }
  }
};

并且在ajax.cgi:中

echo "Content-Type: application/json'n'n"
$username = $_GET("username");
$password = $_GET("password");
if (authenticate($username, $password)) {
  echo "{ '"okay'": true }";
}

为此需要使用AJAX。

$('#submit').on('click', function() {
    $.ajax({
        url: "your/auth/script.php",
        type: "POST",
        success: function(result) {
            if(result !== 1) {
                $(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45);
            }
        }
    });
});