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


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

我正在运行一个数据库,itemID和每个itemID的货架号。

当用户输入itemID时,我希望它通过数据库运行以使用Ajax/PHP获得货架号。然后把货架号贴回来,这样用户就可以看到在哪里可以找到该商品。(这些物品放在一个房间里,标有唯一的标识和共享的货架号。)我需要使用onChange方法(或任何类似的),因为我希望它像提示/搜索引擎一样工作。换句话说,自动…

我是全新的ajax和我似乎不能得到这个工作在所有…没有结果,我现在遇到了障碍。任何形式的帮助都将非常感激

<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);
        };
    })
});