使用javascript返回带有计数的php元素

使用javascript返回带有计数的php元素,php,javascript,mysql,count,Php,Javascript,Mysql,Count,我有一个网站,人们在那里搜索音乐,搜索被记录下来,并附上他们的id。我正试图从中获取信息,到目前为止,它已经奏效了。但是,提要包含一个javascript函数,在该函数中,用户可以将其搜索变成一个链接,单击该链接后,填充搜索字段并完成搜索。问题是我想让每个链接都成为特定的搜索,但最终的结果是它将php变量的值设置为数组中的最后一个搜索。我现在要做的是设置php搜索变量和一个计数器,以便稍后在javascript中调用该变量。我知道这听起来非常混乱/不清楚,但我正在尽力。也许代码会有帮助

我有一个网站,人们在那里搜索音乐,搜索被记录下来,并附上他们的id。我正试图从中获取信息,到目前为止,它已经奏效了。但是,提要包含一个javascript函数,在该函数中,用户可以将其搜索变成一个链接,单击该链接后,填充搜索字段并完成搜索。问题是我想让每个链接都成为特定的搜索,但最终的结果是它将php变量的值设置为数组中的最后一个搜索。我现在要做的是设置php搜索变量和一个计数器,以便稍后在javascript中调用该变量。我知道这听起来非常混乱/不清楚,但我正在尽力。也许代码会有帮助

    $sql_userSearch = mysql_query("SELECT id, searchstring, timecount, userSearch FROM trending WHERE userSearch != 0 ORDER BY timecount DESC LIMIT 50");


    $counter = 1; 
    while($row = mysql_fetch_array($sql_userSearch)){

$search_id = $row["id"];
$searcher_id = $row["userSearch"];
$the_search[$counter] = $row["searchstring"];
$search_date = $row["timecount"];
$convertedTime = ($myObject -> convert_datetime($search_date));
$whenSearch = ($myObject -> makeAgo($convertedTime));
$search_date = $row["timecount"];


$searchDisplayList .= 
'<table style="border:#999 1px solid; border-top:none;" background="img/searchBG.png" cellpadding="5" width="100%">
 <tr>
    <td width="10%" valign="top"><img src="https://graph.facebook.com/'. $searcher_id . '/picture" width="35" height="35"></td>
    <td width="90%" valign="top" style="line-height:1.5em;">
    <span class="liteGreyColor textsize9"><strong>' . $searcher_id . '</strong></a> searched for </span>
    <a href="#" onClick="swapSearch()">' . $the_search[$counter] . '</a></br> ' . $whenSearch . ' 
    </td>
    </tr></table>';


$counter++;
}
稍后,这是我用来返回链接的javascript

     <script type="text/javascript">
    function swapSearch(){
        document.getElementById('s').value = "<?= $the_search[$counter] ?>";
        $('#searchForm').submit();  
    }
    </script>
编辑:

我只是使用了一些javascript来获取链接文本并填充搜索表单。比我想做的容易多了

   <script type="text/javascript">
   $("a.friendSearchLink").live("click",function(a) {       
a.preventDefault();                         
var searchTerm = $(this).text();
document.getElementById('s').value = searchTerm;
$("#searchForm").submit();                  
    });
    </script>

PHP是预处理的,您只能在将页面发送到客户端之前回显一个值。为了完成您想要做的事情,您必须向包含您正在查找的信息的页面发送ajax调用,否则您的输出将完全是静态的。

您可以将$the_search中的所有搜索存储到JS数组中,然后将$counter传入swapSearch“$counter”。然后,您可以在js中查找任何搜索


我唯一的另一个问题是,你是否以帖子的形式提交搜索表?因为如果将其更改为从$\u GET读取,只需设置href=?q=$the\u search[$counter],即可使用该链接运行搜索。另一个选项是在url中传递搜索id,只需使用php加载搜索结果/关键字。

javascript的链接文本显示正确,但是,当您单击链接时,它不会使用正确的文本填充搜索。好吧,假设我使用json编码输出并使用ajax抓取它。如何使每个链接与数组中对应的元素匹配?json数组是JavaScript本机数组,您可以使用jQuery的$.getJSON函数获取对象,然后只需迭代对象。