我有两个 PHP 页面和一个 JavaScript 页面
数据库有1行2列
PHP主要代码
<html>
<head>
<title>Hello!</title>
<script type="text/javascript" src="script/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="script/agent.js"></script>
<link rel="stylesheet" href="css/sheet.css" media="screen"/>
</head>
<body>
<table>
<tr>
<td>agent no. :</td>
<td>
<input type="text" class='agent' name="agent"/>
</td>
<td id='agentname'>agent name</td>
</tr>
</table>
</body>
</html>
和agent.php代码
<?php
$c=mysql_connect("localhost","root","") or die (mysql_error());
$d=mysql_select_db("davidmag_ac") or die(mysql_error());
if(isset($_GET['agent']) and $_GET['agent']<>""){
$agent=$_GET['agent'];
$result= mysql_query("
select agentname
from agent
where agentid=$agent
") or die(mysql_error());
$n=mysql_fetch_assoc($result);
echo $n['agentname'] ;
}
?>
和agent.js代码
$(document).ready(function(){
$(".agent").keyup(function(){
agent=$(".agent").val();
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","agent.php?agent="+agent,false);
xmlhttp.send();
document.getElementById("agentname").innerHTML=xmlhttp.responseText;
});
});
问题是每次我按键时加载代理名称都需要超过一秒(1.3或1.2),所以如果我写12345,当有一行时加载需要6秒
在 phpmyadmin 中,当我尝试此查询时
( 共 1 条,查询耗时 0.0004 秒)
所以每次按键都会有不止一次的浪费。
我真的很想知道为什么?
最佳答案
忽略明显的 SQL 注入(inject)漏洞,尝试使用 mysql_pconnect(),这将保持连接打开:
http://php.net/manual/en/function.mysql-pconnect.php
请注意 mysql_* 函数已被折旧。您应该考虑切换到 MySQLi 或 PDO。
关于php - Ajax 和 MySQL 需要时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730878/