duanduan8439 2016-04-02 15:10
浏览 54

ajax在实时搜索中更新之前读取Json文件

I am writing a live search using jquery Ajax that posts a keyword to php file that writes the result in a JSON file then I read this JSON file as a search result. my problem is Jquery GET from JSON is always retrieve the previous search result

script file

$("#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 file

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

}?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来