首页 文章

AJAX HTML PHP问题

提问于
浏览
-1

This is my scripts.js

function showHint(str)
{
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","inputProcess.php?q="+str,true);
xmlhttp.send();
}

This is my HTML

<script type="text/javascript" src="scripts.js"></script>
<form>
  Type your name here : <input type="text" onkeypress="showHint(this.value)" name="name" />
</form>

This is my PHP file

<?php 
  $q = $_GET['q']; 
 $dbc=mysql_connect("localhost","root","") or die (mysql_error());
  mysql_select_db('input_oop') or die (mysql_error());

  $sql = "INSERT INTO users set name = '".$q."'";
  mysql_query($sql) or die (mysql_error());
  ?>

这是问题:当我在文本框中只键入一个值时,它将多次保存在我的数据库中 .

EG:我输入“Jordan” . 当我签入我的数据库时,它显示为

userid 1 J
userid 2 Jo
userid 3 Jor

等等

3 回答

  • 5

    即使你在那个盒子里做,也会为每个按键开启onkeypress . 所以这是发生的事情:

    • 您键入'j'

    • showHint()被触发,将'j'发送到服务器

    • 该脚本将'j'插入到用户表中

    • 您输入'o',文本字段中现在有'jo'

    • showHint()被触发,将'jo'发送到服务器

    • 脚本将'jo'插入到用户表中

    • 等......

    换句话说,您根本没有显示提示,只是盲目地将用户输入的内容插入到数据库中 .

    如果您想显示提示,那么您应该至少执行“SELECT”查询并将结果返回到您的页面 .

    您还应该使用MootoolsjQuery之类的东西来进行AJAX调用 . 他们'll handle the hard parts of building/sending the request for you, without having to worry about what browser the user'使用 .

    同样,在将诸如你的脚本发布到野外之前,请阅读有关SQL injection的信息 .

    您还有一个格式错误的插入查询 . 要插入新记录,基本语法是:

    INSERT INTO sometable (field1, field2, field3, ...) VALUES (value1, value2, value3, ...)
    

    你在那里混合了一些部分的'更新'查询,其格式是

    UPDATE sometable SET field1=value1, field2=value2, ....
    

    我无法看到您的查询如何像现在一样将任何内容插入数据库,因为语法完全被破坏了 .

  • 0

    根据您使用的浏览器, onkeypress 事件也将触发不改变内容的键,如箭头键,输入或制表键,F5刷新等等...有些浏览器甚至按下shift可能会触发 onkeypress . 有关详细信息,请参见this page .

    由于您的PHP代码不会检查输入的值是否为新值,因此每次按下其中一个键时,它都会添加输入的值 .

    此外,为此使用jQuery是个好主意 .

  • 0
    function sendRequest(str) {
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
       }
     };
     xhttp.open("GET", "inputProcess.php?q="+str, true);
     xhttp.send();
    }
    
    function showHint(str) {
     if (str.length==0) { 
      document.getElementById("txtHint").innerHTML="";
      return;
     } else {
     sendRequest(str)
     }
    }
    

    我知道你要做什么,请使用标准方法......代码中唯一的问题实际上是onKeypressed . 当你确定用户完全输入了这个词并且不再打字时,你需要调用请求我不认为它在JS中很容易,你当然可以使用很多工时来完成 .

相关问题