我开始探索ajax,不知何故我对它很好,不是太难也不容易,只是正常的。无论如何,我在这个项目上遇到了困难。涉及到ajax、php、js、mysql。我实际上是在尝试复制 Facebook 的标记风格。当您在帖子中标记某人时,全名会变成指向标记用户个人资料的超链接。我觉得这只是一个小问题,只是我也是 JS 的新手。我已经完成了其余的工作,但是在将文本转换为带有 js 的超链接时遇到了问题。我希望它在 putin_livesearch() 代码中。
这是我的代码。
索引.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FB TAG</title>
<style>
.namesearch {
cursor:pointer;
}
</style>
<script type="text/javascript">
function putin_livesearch(fname, lname)
{
//document.getElementById('searchbar').value = (fname + " " +lname);
//document.location.href='#'+ window.document.getElementById('searchbar').value = (fname);
window.document.location.href="#"+window.document.getElementById('searchbar').value;
}
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
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("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input id ="searchbar" name="wallpost" type="text" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>
</body>
</html>
获取用户.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("place_main", $con);
$sql=" SELECT * FROM profiles WHERE firstname like '".$q."%' ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$fname = $row['firstname'];
$lname = $row['lastname'];
echo '<span class ="namesearch" onclick="putin_livesearch(\''.$fname.'\',\''.$lname.'\' )"> '. $fname ." ". $lname .' </span><br />';
//echo "<span class ='namesearch' onclick='putin_livesearch(" .$fname. ", " .$lname. " )'> " . $fname . " " . $lname . "</span><br />";
}
mysql_close($con);
?>