0

我正在构建一个基于 Web 的系统。在这里我在想是否可以根据我在文本框中输入的数字来获取名称。我尝试过的如下。我知道它不起作用。会有另一种解决方法吗?请帮忙...

html代码是

    Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
    Item Name:<input name="na" type="text" id="na" size="40" maxlength="40"  disabled>

这是我的 javascript

function namesrch(){
            iNumber = document.getElementById('iNo').value;
            document.getElementById('na').value="<?php $SQL="SELECT iName FROM item Where iNo='iNumber'" ; $run=mySQL_Query($SQL,$con) or die ("SQL error"); while($rec=mySQL_fetch_array($run)){echo $rec{'iName'}}?>";
        }

希望你能理解我想要做什么。提前致谢..

4

2 回答 2

0

JavaScript 是一种客户端语言,而 PHP 是一种服务器端语言。你不能像那样在 JavaScript 中运行 PHP。你需要的是Ajax

这是一个简单的例子:

Javascript

$('#iNo').on('update', function() {
    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: { no: $(this).val() }
        success: function(name) {
            $('#na').val(name);
        }
    });
});

ajax.php

$dbConn = new MySqli($host, $username, $passwd, $dbName);
$no= filter_input(INPUT_POST, "no", FILTER_VALIDATE_INT);
$query = "SELECT iName FROM item WHERE iNo = $no";
$result = $dbConn->query($query);
$name = '';
if($dbConn->errno) {
    //An error occurred
} elseif($result->num_rows) {
    $row = $result->fetch_assoc();
    $name = $row['iNo'];
    $result->free();
}

echo $name;

你会注意到我使用了MySQLi,而不是 MySQL。MySQL 已贬值,不应再使用。值得您花时间学习使用MySQLiPDO

我希望这有帮助。

于 2013-11-13T16:56:40.483 回答
0

You can't mix php and js. Assuming you want all the code in one file:

filename.php (Not tested)

<?php 
    if (isset($_GET['iNumber'])) {

        $mysqli = new mysqli("localhost", "my_user", "my_password", "database_name");

        // You need to check for sql injection here

        $SQL = "SELECT iName FROM item Where iNo = '".$_GET['iNumber']."'' LIMIT 1"; 

        $result = $mysqli->query($query);

        $row = $result->fetch_assoc();

        echo json_encode(array('iName' => $row['iName']));

        exit();
    }
?>
<html>
<head>
    <title></title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
    Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
    Item Name:<input name="na" type="text" id="na" size="40" maxlength="40"  disabled>
    <script type="text/javascript">
        function namesrch() {
            iNumber = document.getElementById('iNo').value;

            $.getJSON('filename.php?iNumber='+iNumber, function(response) {
                $('#na').value(response.name);
            });
        }
    </script>
</body>

</html>
于 2013-11-13T17:00:36.520 回答