如何从我的外部 javascript 文件访问 php 变量。
这是我的 getting.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> <br/><?php echo $email; ?><br/>
</div>
<?php
}
}
?>
我想在我的 getting.js
文件中使用 $username
。我如何访问它。请告诉我。
最佳答案
我喜欢 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/