简体   繁体   中英

After ajax page allready reloads.

I'm just exploring ajax to learn it.

I try the following JavaScript test code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Ajax Demo</title>
<meta name="" content="">
<script type="text/javascript">

function aa(){

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.open("GET","getprod.php",false);
xmlhttp.send();

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
</script>
</head>
<body>

<form>
    <input type="text" name ="txta"  onchange="aa();">  </input>
    <br>
    <div id ='myDiv' style="width: 400px;height: 300px; overflow-y: auto;border: #e87517 1px solid"> 

  <?php
      $mysqli=new mysqli('localhost', 'root', 'password', 'ajax');
      if ($mysqli->connect_errno) {
      die("Connect failed". $mysqli->connect_error);
      }
      $mysqli->set_charset("utf8");

  if ($result = $mysqli->query("select id, name from test;")){
      while ($row = $result->fetch_assoc()) {
      echo $row['id'], " - " , $row['name'], "<br>";
      }//while 
  }//if 

   $result->close(); 
   $mysqli->close();
   ?>   
 </div> 
 </form>
</body>
</html>

And a few Row For "getprod.php".

  <?php
   echo "123";
   ?>

When I change the value in textbox, Ajax returns me the string "123", as desired and places it in div, but after few seconds, div is again filled with results from MySQL, that's not desired.

1) What's wrong in my code? (Goal is: When I change value in textbox, only returned string from ajax - "123" must be appear in div container permanently.) 2) Textbox change event occurs when it loses focus or when I press ENTER on keyboard. How to fire change event without this action?

Thanks in advance.

  1. There is nothing in the code you posted that will cause the page to reload.

  2. "without this action" - but when? Consider using oninput event - http://www.w3schools.com/jsref/event_oninput.asp .

尝试将onchange事件更改为onkeypressoninput

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM