Ajax请求和显示结果(无需重新加载页面)


Ajax request and displaying result (no page reload)

我目前有一个动态字段,其中的值是从mysql数据库中提取的。我正在运行一个查询,通过php查找名为person的表的下一个Auto_Increment字段。由于Auto_increment可以由于来自不同插入查询的事务而随时改变。如何执行ajax请求以从php文件中获取下一个自动增量值并显示结果?

nextAutoIncrement.php

$tablename          = "person";
$next_increment     = 0;
$qShowStatusResult  = $db_con->prepare("SHOW TABLE STATUS LIKE '$tablename'");
$qShowStatusResult->execute();
$results = $qShowStatusResult->fetchAll('PDO::FETCH_ASSOC);
foreach($results as $value) {
    $next_increment = $value['Auto_increment'];
}
echo $next_increment;

jquery/ajax

// Create an object to describe the AJAX request
var ajaxAutoIncrement = {
    url: "nextAutoIncrement.php",
    dataType: "text",        
    success: function(result) {
        $("#results").text(result);
    },
};
// Initiate the request!
$.ajax(ajaxAutoIncrement);

在此处显示结果:

<input type="text" name="results" id="results" value="">

setTimeout()可能有助于

   success: function(result){
          $("#results").text(result);
          // 3 seconds interval
           setTimeout(ajaxAutoIncrement,3000); 
     }

您可以做的是将数据传递给PHP脚本,该脚本将从数据库中获取数据并返回一个响应,该响应将显示在特定的div标记

之间

假设您的主页面如下:

<html>
<head>
<script>
function showUser(str)
{
if (str=="")
  {
  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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>

您的PHP脚本应该如下:

<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";
mysqli_close($con);
?>