按下/扫描返回键时的自动选项卡(php / mysql / javascript)

时间:2011-08-04 12:42:57

标签: php javascript mysql html ajax

希望你再次帮助我解决过去几周我一直在努力解决的问题..

我有一个简单的基于网络的数据库,我用它来记录离开仓库的产品的序列号。该系统位于我们的防火墙之后,我并不关心SQL注入或类似的事情。

目前,网络表单包含以下字段:

第1行:产品UPC(R_UPC) 第1行:产品序列号(R_SerialNumber) 第2行:产品部件号(R_PartNumber) 第2行:产品描述(R_Description) 第3行:专家(R_Specialist) 第3行:实现(R_FulfilledBy)

当我们扫描产品的条形码时,零件编号和描述字段通常是从“产品”数据库中的数据完成的,但是自动选项卡功能会中断此查找。我确信这是一个简单的解决方案,但我只是无法弄明白......

条形码扫描仪配置为在扫描条形码时自动按返回,然后搜索“产品”数据库以进行匹配。所以我希望它能够在扫描UPC字段后自动标记到下一个输入字段(产品序列号),一旦序列号被扫描,它将自动标记3个框(到专家字段)。

我已经成功地完成了这项工作 - 在相应的字段选项卡上输入正确的框。但是,执行查找以填充“零件号”和“描述”输入字段。

这背后的目标是提高网络表单的效率和一般易用性,这样我们就不需要继续按Tab键了。我还想在“Part Number”和“Description”字段中使用像innerText / AJAX这样的东西,以便用户不会意外地编辑它们,从而减少垃圾数据的可能性。

以下是可能相关的信息:

<!-- Tab on Return -->
<SCRIPT LANGUAGE="JavaScript">
nextfield = "R_UPC"; // name of first box on page
netscape = "";
ver = navigator.appVersion; len = ver.length;
for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
netscape = (ver.charAt(iln+1).toUpperCase() != "C");

function keyDown(DnEvents) { // handles keypress
// determines whether Netscape or Internet Explorer
k = (netscape) ? DnEvents.which : window.event.keyCode;
if (k == 13) { // enter key pressed
if (nextfield == 'done') return true; // submit, we finished all fields
else { // we're not done yet, send focus to next box
eval('document.req_form.' + nextfield + '.focus()');
return false;
  }
 }
}
document.onkeydown = keyDown; // work together to analyze keystrokes
if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);
</script>

<!-- Autocomplete Specialist Field -->
<script type="text/javascript">

// FUNCTION: Get product info from UPC
function productDetails(UPC){

// SEND AJAX REQUEST, POST UPC
$.ajax({
    type: "POST",
    url: "../includes/get_product_detail.php",
    data: "UPC=" + UPC,
    dataType: 'json',
    success: function(data){

        // FROM JSON STRING RETURN DESCRIPTION AND ADD TO form_description INPUT
        $('#form_description').val(data.description);
        $('#form_part').val(data.part_number);

    }
});

}

$(document).ready(function() {

// ADD KEYPRESS EVENT HANDLER
$('#form_upc').keypress(function(event) {
    // IF RETURN KEY IS PRESSED, FIRE productDetails FUNCTION
    if (event.which == '13') {

        // FIRE FUNCTION USING VALUE IN form_upc
        productDetails($('#form_upc').val());

    }
});
// Autocomplete Specialist Field
$("#form_specialist").autocomplete("../includes/get_specialist_list.php", {
    width: 260,
    matchContains: true,
    mustMatch: true,
    //minChars: 0,
    //multiple: true,
    //highlight: false,
    //multipleSeparator: ",",
    selectFirst: false
});


});
</script>
<!-- End -->

<!-- Disable Enter Button on Barcode Scanners causing accidental submission of data to database -->
<script language="JavaScript">

function disableEnterKey(e)
{
 var key;     
 if(window.event)
      key = window.event.keyCode; //IE
 else
      key = e.which; //firefox     

 return (key != 13);
}
</script>
<!-- End -->

<!-- Input Validation -->
<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{

// ** Validate Part Number Entry **
if (form.form_part.value == "") {
 alert( "Please enter Product Part Number" );
 form.form_part.focus();
 return false ;
}
if (form.form_part.value == "Invalid UPC") {
 alert( "INVALID Data Entered - Please Rescan UPC" );
 form.form_part.focus();
 return false ;
}
// ** END Part Number Validation **

// ** Validate Specialist Entry **
if (form.form_specialist.value == "") {
 alert( "Please enter Specialist Name" );
 form.form_specialist.focus();
 return false ;
}
// ** END Specialist Validation **

// ** Validate Fulfilled By Entry **
if (form.form_bohspecialist.value == "") {
 alert( "Please enter BoH Specialist Fulfilling Order" );
 form.form_bohspecialist.focus();
 return false ;
}
// ** END Fulfilled By Validation **
return true ;
}
//-->
</script>
<!-- END -->

这是get_product_detail.php:     

// VARIABLES
include("main.config.inc.php");

// connect to the MySQL server
$cxn = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass)
or die ("Sorry, could not connect to the server.");

// connect to the DB
$db = mysql_select_db($runnerdbName, $cxn)
or die ("Sorry, could not connect to the correct database.");

// GET UPC
$upc = $_POST['UPC'];

$sql = "SELECT * FROM Products WHERE P_UPC = '$upc'";

$result = mysql_query($sql) or die ('Product could not be queried');
$num = mysql_num_rows($result);

// ONLY ONE PRODUCT SHOULD MATCH
if ($num == 1){

$row = mysql_fetch_assoc($result);

$json['upc'] = $row['P_UPC'];
$json['part_number'] = $row['P_PartNumber'];
$json['description'] = $row['P_Description'];


} else {

// DUPLICATE ENTRIES?
$json['upc'] = 0;
$json['part_number'] = "Invalid UPC";
$json['description'] = "Invalid UPC";

}

// GENERATE JSON STRING
echo json_encode($json);

?>

这是html表单方面的事情:

<form name ="req_form" autocomplete="off" action="../includes/new_request.php" method="post">
        <table width="100%" border="0">

          <tr>
            <td>* Product UPC: <br />                   <input type="text" name="R_UPC" onFocus="nextfield ='R_SerialNumber';" id="form_upc"/></div></td>
            <td>Product Serial Number: </br />                  <br/><input type="text" name="R_SerialNumber" onFocus="nextfield ='R_Specialist';" id="form_serial"/></div></td>
          </tr>
          <tr>
            <td>* Product Part Number: <br />                 <input type="text" name="R_PartNumber" id="form_part" /></div></td>
            <td>Product Description: <br />               <input type="text" name="R_Description" id="form_description"/></div></td>
          </tr>
          <tr>
            <td>* Specialist: <br />                  <input type="text" id="form_specialist" name="R_Specialist"  onFocus="nextfield ='R_FulfilledBy';"/></td>
            <td>* Fulfilled By: <br />
            <?php

                // Connect to DB
                connecttodb($runnerdbServer,$runnerdbName,$runnerdbUser,$runnerdbPass);
                function connecttodb($runnerdbServer,$runnerdbName,$runnerdbUser,$runnerdbPass)
                {
                global $link;
                $link=mysql_connect ("$runnerdbServer","$runnerdbUser","$runnerdbPass");
                if(!$link){die("Could not connect to MySQL");}
                mysql_select_db("$runnerdbName",$link) or die ("could not open db".mysql_error());
                }

                $tp=$_GET['U_Name']; // getting the value from query string
                $query="SELECT U_Name FROM Users ORDER BY U_Name ASC";
                $result = mysql_query ($query);
                ?>

                <select name="R_FulfilledBy" id="form_bohspecialist">
                <?
                while($nt=mysql_fetch_array($result)){

                echo "<option value='$nt[U_Name]'>$nt[U_Name]</option>";

                }
                echo "</select>";

            ?>
            </td>
          </tr>

            <td><input type="submit" id="form_submit" value="Submit" /></td>
          </tr>
      </table>
            </form>

非常感谢任何帮助! :)

1 个答案:

答案 0 :(得分:0)

我认为没有一个很好的解决方案。当您根据默认排序和特殊tabIndex属性点击选项卡时,浏览器会逐步执行表单元素。应该可以重新创建这种行为,但我会告诉你这一点。

// since you already are using jQuery, also use it to bind event handler
$('form[name=request_form').bind('keyup', function (e) {
  // jQuery normalizes e.which for you
  if (13 === e.which) {
    // get idnex of the element that triggered the event
    // use Array method indexOf for this
    var currentIndex = Array.prototype.indexOf.call(this.elements, e.target);
    // have we stepped through all form elements?
    if (currentIndex >= this.elements.length) {
      // submit form, should happen through default action
      // if not, uncomment the following line.
      // this.submit();
    } else {
      // focus next element
      form.elements[currentIndex + 1].focus();
    }
  }
});

我同意评论员的意见:即使应用程序在防火墙内,你也应该防止SQL注入。甚至您的员工也可能会尝试转储您的数据库,或者攻击者可以穿透/绕过您的防火墙。