繁体   English   中英

如果用户使用Ajax / PHP向文本输入输入INT,如何从DB获取ID?

[英]How to get ID from DB if user enters INT to text input using Ajax/PHP?

我正在运行一个带有itemID和每个itemID的架子号的数据库。

当用户输入itemID时,我希望它通过Ajax / PHP在我的数据库中运行以获取架子号。 然后将货架号发回,以便用户可以在哪里找到该物品。 (这些项目在一个房间里,并标记有唯一的ID和共享的货架号。)由于我希望它像小费/搜索引擎一样工作,因此我需要使用onChange方法(或类似的方法)。 换句话说自动

我对ajax完全陌生,我似乎根本无法使它正常工作。.没有给出任何结果,我现在处于障碍之中。.非常感谢任何形式的帮助

的HTML

<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
    $.ajax({
        url: 'shelfid.php',
        type: 'POST',
        dataType: 'JSON',
        data:{ 
            itemID: $(this).val() 
        },
        success:function(response) {
            alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
        }
    });
});
</script>
</head>
    <body>
        <a>Enter Item ID 1:</a> 
        <input id="target" type="text" name="itemID" required />    
        <div id="hyllplacering">ENTER Shelfnumber here: </div>
    </body>
</html>

的PHP

<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>

遇到JavaScript便立即执行。 您将事件绑定到元素之前,该事件才可用。 您需要将脚本包装在document.ready主体中。

正如提到的其他答案一样,您想使用success回调而不是done

<script>
$(document).ready(function(){
    $('#target').change(function() {
        $.ajax({
            url: 'shelfid.php',
            type: 'POST',
            dataType: 'JSON',
            data:{ 
                itemID: $(this).val() 
            };
        })
        .success(function(response) {
            alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
        });
    });
});
</script>

您可以在AJAX函数中添加一个句子

$.ajax({
        url: 'shelfid.php',
        type: 'POST',
        dataType: 'JSON',
        data:{ 
            itemID: $(this).val() 
        };
        success:function(data){
            console.info(data);
        }
    })

监视PHP响应的内容,更容易检查出问题所在。

我认为您不正确使用Ajax对象的done方法。 我很确定您不会在该范围内提供您的答复。 尝试做..

$('#target').change(function() {
    $.ajax({
        url: 'shelfid.php',
        type: 'POST',
        dataType: 'JSON',
        data:{ 
            itemID: $(this).val() 
        },
        success:function(response) {
            alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
        },
        error:function(response){
            alert('error '+response);
        };
    })
});

暂无
暂无

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

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