【问题标题】:Populate one fieled when other related field is entered输入其他相关字段时填充一个字段
【发布时间】:2014-12-07 19:47:35
【问题描述】:

我的数据库中有两个字段 卷号和名称 我设计了一个 html 表单,其中有两种输入类型 一——>“卷号” 另一个是“名称”

我希望当我在卷号字段中输入卷号并按 Tab 时,名称字段应自动填满,从数据库中获取。

我的代码在这里

index.php

<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script> 
<script type="text/javascript">
var searchTimeout; //Timer to wait a little before fetching the data
$("#roll").keyup(function() {
    searchKey = this.value;

    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(function() {
        getUsers(searchKey);    
    }, 400); //If the key isn't pressed 400 ms, we fetch the data
});

function getUsers (searchKey) {
    $.ajax({
        url: 'getUser.php',
        type: 'POST',
        dataType: 'json',
        data: {value: searchKey},
        success: function(data) {
            if(data.status) {
                $("#name").val(data.userData.name);
            } else {
                // Some code to run when nothing is found
            }   
        }
    });         
}
</script>
</head>             

<table>
<tr>
    <td>Roll</td>
    <td><input type="text" name="roll" id="roll" /></td>
</tr>

<tr>
    <td>Name</td>
    <td><input type="text" name="name" id="name" /></td>
</tr>
</table>
</html>

getUser.php

<?php
include "db.php";

$response = Array();

$response['status'] = false;

$query = mysql_query("SELECT `name` FROM `tab` WHERE `roll` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search

if(mysql_num_rows($query)) {
    $userData = mysql_fetch_assoc($query);

    $response['userData'] = $userData;
    $response['status'] = true;            
}

echo json_encode($response);
?>

【问题讨论】:

  • 听起来像是 AJAX 的工作
  • 但是如何?我该怎么做呢
  • 广义地说,你需要做一些工作尝试一下,如果\当你遇到问题时用 code

标签: javascript php html database


【解决方案1】:

您可以使用ajax.AjaxPHP 实时通信,这样名称字段将自动填写,而无需按下提交按钮。

XMLHttpRequest() 是完成此任务所需的函数。请对XMLHttpRequest() 进行一些研究,这将有助于您获得更好的想法。

function auto(roll){
  var roll=roll;
  var ajax=new XMLHttpRequest();
  ajax.open("post","yourfile.php",true);       
  ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");
  ajax.onreadystatechange=function(){
    if(ajax.readyState == 4 && ajax.status == 200){
      document.getElementById(Name).value=ajax.responseText;  //This line will fill the Name field automatically
     }
  }

  ajax.send("roll_num="+roll);
}

因此,在这种情况下,在您的 php 文件 yourfile.php 中,为该 roll 获取 nameecho name 在 php 文件中,并且 name 值将传递给 ajax asynchronously。然后 name 字段将自动填充

这就是您获得预期结果的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2021-08-09
    相关资源
    最近更新 更多