如何从外部javascript文件访问php变量。
这是我的get.js文件

$(function(){

$(".search").keyup(function()

{

var searchid = $(this).val();

var dataString = 'search='+ searchid;

if(searchid!='')

{

    $.ajax({
    type: "POST",
    url: "search.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html).show();
    }
    });
}return false;
});

这是我的search.php文件。
<?php

include('db.php');

if($_POST)
{

$q=$_POST['search'];

$sql_res=mysql_query("select id,name,email from detail where name like '%$q%' or email like '%$q%' order by id LIMIT 5");

while($row=mysql_fetch_array($sql_res))

{
$username=$row['name'];

$email=$row['email'];

$b_username='<strong>'.$q.'</strong>';

$b_email='<strong>'.$q.'</strong>';

$final_username = str_ireplace($q, $b_username, $username);

$final_email = str_ireplace($q, $b_email, $email);

?>
<div class="show" align="left">

<span class="name"><?php echo $username; ?></span>&nbsp;<br/><?php echo $email; ?><br/>

</div>

<?php

}

}

?>

我想在我的$username文件中使用getting.js。我该如何访问它。请告诉我。

最佳答案

我喜欢php,它根本不知道html。
尝试将search.php改为返回json而不是html:

...
$result = array('users' => array(), 'method'=>'search');
while($row=mysql_fetch_array($sql_res))
{
  $result['users'][] = $row;
}
header('Content-type: application/json; charset=UTF-8');
echo json_encode($result);

并用javascript处理所有接收到的数据:
success: function(json) {
 var data = JSON.parse(json);
 console.log(data);
 // change DOM with new data etc.
}

关于javascript - 如何从我的外部javascript文件访问php变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27572332/

10-09 16:46
查看更多