【问题标题】:How to do jQuery autocomplete using an AJAX call to a PHP script?如何使用对 PHP 脚本的 AJAX 调用进行 jQuery 自动完成?
【发布时间】:2016-07-22 23:57:20
【问题描述】:

我有以下用于自动完成的 jQuery 代码,

$( "#text" ).autocomplete({
      source: function( request, response ) {
        $.ajax({
          type: 'GET',
          url: 'server.php',
          dataType: 'json',
          data: {
            input: request.term
          },
          success: function(data) {
          response( $.map(data, function(item) {
            return {
              label: item.Symbol + " - " + item.Name + " ( " + item.Exchange + " )"
            }
          }));
        }
        });
      },
      minLength: 1,
      select: function( event, ui ) {
           var symbol = ui.item.label.split(' ');
               setTimeout(function() {
                   $('#text').val(symbol[0]);
               },0);
      }
    });

只要用户在文本框中输入一个键,就会对 PHP 文件进行 AJAX 调用。此 PHP 文件将从 API 检索数据并更新自动完成功能的建议列表?

我在PHP端有以下代码,

<?php
if(!empty($_GET['term'])) {
        $term = $_GET['term'];
        $url = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=".$term;

        $j_response = file_get_contents($url);
        $j_response = json_decode($j_response);

        print json_encode($j_response);

    }
?>

由于某种原因,自动完成功能对我不起作用-我在这里做错了什么?

【问题讨论】:

    标签: php jquery ajax autocomplete


    【解决方案1】:

    在 PHP 中,您尝试使用 $_GET['term'],但在 JavaScript 中,您的变量称为 input。将数据对象更改为使用term 而不是input

    data: {
      term: request.term
    },
    

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 2012-01-14
      • 2022-09-23
      • 2012-06-04
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多