Javascript将文本从db转换为超链接

时间:2012-09-23 15:15:14

标签: php javascript ajax

我开始探索ajax,不知怎的,我对它很好,不是太难,也不容易正常。无论如何,我对这个项目有困难。它涉及ajax,php,js,mysql。我实际上是在试图复制Facebook的标记风格。当您在帖子中标记某人时,全名将变为指向标记用户个人资料的超链接。这只是我觉得的一个小问题,它只是我对JS的新手。我已经完成了其余的工作,但是我在将文本转换为带有js的超链接时遇到了问题。我想在putin_livesearch()代码中使用它。

这是我的代码。

的index.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>

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

2 个答案:

答案 0 :(得分:0)

在你的PHP上,只需做这样的事情

echo "<a href='your-url-for-the-user'><span class ="namesearch" onclick="putin_livesearch(\''.$fname.'\',\''.$lname.'\'  )"> '. $fname ." ". $lname .' </span></a><br />";

只需在PHP中操作它,我就相信它会在你的前端输出相同内容。

答案 1 :(得分:0)

好吧,我想我想要的是不可能的。为了测试,我实际上尝试在带有标记的文本区域中添加值。它不会将其转换为链接。实际上用fb标记了一个用@在墙上的朋友来检查fb并没有把它放到一个链接上,但是之后发布的时候确实如此。