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

时间:2013-12-04 04:50:28

标签: php jquery ajax

我目前有一个动态字段,其中包含从mysql数据库中获取的值。我正在运行一个查询,通过php查找名为Auto_Increment的表的下一个person字段。由于来自不同插入查询的事务,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="">

3 个答案:

答案 0 :(得分:1)

setTimeout()可能会帮助你

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

答案 1 :(得分:-1)

您可以做的是,将数据传递给PHP脚本,该脚本将从数据库中获取数据并返回将在某些div标签之间显示的响应

答案 2 :(得分:-1)

假设您的主页如下:

<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);
?>