gpt4 book ai didi

php - JQuery验证插件: Use remote with delay

转载 作者:行者123 更新时间:2023-12-01 05:30:24 24 4
gpt4 key购买 nike

我正在使用remote method来自jQuery validation plugin进行 ajax 调用。每次在输入字段中按下按键时都会激活远程功能。我想添加一个延迟,以便只有当用户停止按键几毫秒时才会触发 ajax 请求。

这个问题是在2012年提出的at GitHub但于 2015 年被开发商关闭:

I'm sorry for the lack of activity on this issue. Instead of leaving it open any longer, I decided to close old issues without trying to address them, to longer give the false impression that it will get addressed eventually.

在论坛中,用户lohfu提出了以下解决方案:

$.validator.methods._remote = $.validator.methods.remote;

var timer = 0;
$.validator.methods.remote = function () {
clearTimeout(timer);

var args = arguments;

timer = setTimeout(function() {
$.validator.methods._remote.apply(this, args);
}.bind(this), 500);

return "pending";
};

但是,有两个主要问题:

  1. 这不起作用。如果我添加延迟并且远程函数返回 false,则表单仍会提交。

  2. 当我在输入字段中输入一些导致远程函数出错的内容时,它会正确分配 class="error" 。如果我现在选择不同的输入,class="error" 会切换到 class="valid",尽管错误消息仍然存在并且仍然显示错误消息。当我按下提交时也会发生同样的情况。

<小时/>

这是一个最小的例子:

HTML

<form action="test.php" method= "POST" id="form">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit">
</form>

JS

    $("#form").validate({
rules: {
name: "required",
email: {
required: true,
email: true,
remote: {
url: "ajax.php",
type: "post"
}
}
},
messages: {
email: {
remote: "Email already exists"
}
}
});

ajax.php

<?php
header('Content-Type: application/json');

$valid = null;

echo json_encode($valid);

永远不要提交此表单,因为 ajax.php 总是返回 false。但是,输入姓名和有效电子邮件将提交表单,尽管显示错误“电子邮件已存在”。

最佳答案

以下 fiddle 是否按预期工作?您可以将 url 更改为 true 或 false:

url: '/echo/js/?js=[null|true|false]',

https://jsfiddle.net/ww0zh9jm/2/

..您必须添加外部资源(Fiddle 将其删除): https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js

关于php - JQuery验证插件: Use remote with delay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37923177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com