0

我有一个文本字段类型的文本,当我输入一个盘子的数字时,如果它存在,它必须显示一个警报,但事件 keyup 不起作用。

JS

$('#mat').keyup(function(){
        var matric = $('#mat').val();
        $.ajax({type: "POST",
                     url: "compruebaVeh.php",
                     data: "matric="+matric,
                     success:function(data) {
                         alert(data);
                         if(data=='ok'){
                             alert('this car already exists');
                         }
                     }
        });  
    });

PHP

<?php

 $mat=$_POST['matric'];
 ini_set('display_errors',1); error_reporting(E_ALL);
 require('conecta.php');
 $cSQL="select matricula from vehiculos;";
 $stmt=$oConni->prepare($cSQL) or die($oConni->error);
 //$stmt->bind_param('s',$_POST['matric']);
 $stmt->execute();
 $stmt->bind_result($matricula);
 while ($stmt->fetch()) {
    if($matricula==$mat){
        echo 'ok';
    }
 }   
 $stmt->close();  
?>
4

5 回答 5

2

在 php 代码中,赋值$_POST['matric']=$mat;应该颠倒

$mat = $_POST['matric'];

根据数据库中的数据,您的脚本可能会ok多次回显,循环应变为:

while ($stmt->fetch()) {
    if($matricula==$mat){
        echo 'ok';
        break;
    }
 }  

所以现在你可以在 js 回调中与“ok”进行比较。

于 2013-03-12T17:32:41.327 回答
1

我要解决这个问题,这样你就不会像这样设置后端那样敲打你的后端。关于 SO的问题已经解决了这个问题

//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 second for example

var licenceSearch = $("#mat");

//on keyup, start the countdown
licenceSearch.keyup(function () {
    clearTimeout(typingTimer);
    if (licenceSearch.val) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping() {
    alert(licenceSearch.val());

    // ajax stuff can happen here.
}
于 2013-03-12T17:49:52.173 回答
0

您需要使用新的Promise 接口JQuery 方法,如下所示:

$('#mat').on('keyup', function (event) {

    var matric = $(event.target).val();

    var response = $.post("compruebaVeh.php", {data: matric});

    response.done(function (data) {
        alert(data)
    });

    response.fail(function () {
        alert('error')
    });

});

这是一个有效的 keyup fiddle 示例: http: //fiddle.jshell.net/vHTZN/

于 2013-03-12T17:31:54.213 回答
0

在 php 代码中创建退出语句,然后重试。

while ($stmt->fetch()) {
    if($matricula==$mat){
        echo 'ok';
    }
 }  
exit; 
于 2013-03-12T17:34:39.457 回答
0

在大多数情况下,在 html 代码中不止一次定义了 id #mat,keyup 也可能有效,但 url 可能不正确,并且不会触发成功分支。除此之外,我看到 $_POST['matric']=$mat; 这不太对。可能你想要 $mat = $_POST['matric']。您可以使用 firebug 控制台检查 javascript 的实际情况以及 php 脚本返回的内容

于 2013-03-12T17:37:00.643 回答