我正在使用jquery Ajax编写实时搜索,将关键字发布到php文件,将结果写入JSON文件然后我将此JSON文件作为搜索结果读取。 我的问题是来自JSON的Jquery GET总是检索以前的搜索结果
脚本文件
$("#searchArea").keyup(function() {
var searchKeyword = $(this).val();
if (searchKeyword.length > 0) {
$.post('livesearch.php', { keywords: searchKeyword });
$.getJSON('livesearch.json',function(data){
var resultBox = $('#searchReasult');
var output = '<ul>';
$.each(data, function(key, val){
output += '<li>';
output += '<h3>' + val.username + '</h3>';
output += '</li>';
})
output += '</ul>';
$('#update').html(output);
console.log(output)
if(searchKeyword.length=0){$('#update').hide;}
})
}
if(searchKeyword.length=0){$('#update').hide;}
PHP文件
<?php
require_once('includes/database.php');
require_once('includes/USER.php');
$key = (isset($_POST['keywords']))? $_POST['keywords']:null;
if(isset($key)){
global $database;
$esc_key = $database->escape_value($key);
$sql = "SELECT * FROM user ";
$sql .= "WHERE username LIKE '%$esc_key%' OR ";
$sql .= " first_name LIKE '%$esc_key%' OR ";
$sql .= " last_name LIKE '%$esc_key%' ";
$sql .= "LIMIT 10 ";
$result = USER::find_by_sql($sql);
foreach($result as $user){
$user->password = null;
}
$fp = fopen('livesearch.json', 'w');
fwrite($fp, json_encode($result));
fclose($fp);
}?>