dskld5423 2018-07-18 04:50
浏览 402
已采纳

ajax请求,查询数据库,json_encode,成功返回,显示结果

I'm working on a new piece of code and I'm new to ajax so I cant get it to work. I've got a textbox that has a javascript onKeyUp assigned to it. The first function is a delay function. It sets a delay timer, and as long as no other request is made via that delay timer, it runs a second function with the ajax after a certain time period. Inside the ajax, it runs a database query located in the second file based on the text that was entered in the textbox. It sets up an array of the results, json_encodes them, and returns them back to the original page. Then, I need to populate the page with the results (with php).

The Textbox

<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />

The delay function

<script type="text/javascript">
function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  callback();}}, time||500);
  }
</script>

The ajax function

<script type="text/javascript">

function search_customer(value){    

console.log(value); 

    $.ajax({
  type: "POST",
  url: "secondpage.php",
  data: query,
  dataType: 'json',
  success: function(data){
    console.log(data.name); // customer name
    console.log(data.company);   // customer company name
  }
});
}

</script>

second page

set up an array for testing. Bypassing the query for now. Just need to get results back into main page. I can set up the array from the php once its working. My query will use LIKE %search text%

$arr = array(
  'name'=>'overflow',
  'company'=>'value'
);
echo json_encode($arr);

I have NO clue how to retrieve the data from the ajax function and populate the results. I would love to get the results back into a php array, and then loop through the array to echo out the results. I can loop through the array in php...my biggest concern is getting the results back into a php array.

Any assistance would be great. I cant seem to get the code to work. I am new to ajax so I'm learning this as I go.





UPDATE

Everything is working the way it should except the delay. Its not putting a delay on anything. I need it to wait for 2 seconds from each keyup before it activates the ajax function. If it receives another keyup, it waits an additional 2 seconds. IT continues until there is 2 seconds with no keyups. That way its not querying the database on every single keyup if the person is still typing. Right now its processing everything with each keyup.

textbox

<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />

delay

function delay_method(label,callback,time){
    if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}  
    delayed_methods[label]=Date.now();
    var t=delayed_methods[label];
    setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{  callback();}}, time||500);
  }

ajax function

function search_customer(value){    

console.log(value); 

    $.ajax({
  type: "POST",
  url: "secondpage.php",
  data: { "value": value },
  dataType: 'html',
  success: function(data){
      $('#resultDiv').html(data);
  }
});
}

second page:

$value = $_POST['value'];

if ((isset($value)) && ($value != "")) { 
$arr = array();
$search_query = $db1q->query("SELECT first_name, company FROM Users WHERE first_name LIKE '%$value%' OR last_name LIKE '%$value%' OR company LIKE '%$value%'");
if ($search_query->num_rows > 0) {

    while ($search_result = $search_query->fetch_assoc()) {
$arr[$search_result['first_name']] = $search_result['company'];
    }
}

   $html = '';
    $html .= '<div>';
    foreach ($arr as $key => $value) {
        $html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
    }
    $html .= '</div>';

echo $html;
}
  • 写回答

3条回答 默认 最新

  • dongtieshang5429 2018-07-18 05:05
    关注

    You can't get the results back into a php array in js. So, what you have to do is to pass processed html in js and just print on page.

    For example, In second page

    $arr = array(
      'name'=>'overflow',
      'company'=>'value'
    );
    

    using above array $arr make html over here and store it in variable. pass that variable into js.

    For Ex :

        $html = '';
        $html .= '<div>';
        foreach ($arr as $key => $value) {
            $html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
        }
        $html .= '</div>';
    
    echo $html;
    

    Now you will get html in your ajax success. just show on div like

    $('resultDiv').html(data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败