2016-04-03 96 views
2

我有以下的jQuery代碼自動完成,如何使用AJAX調用PHP腳本來實現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); 
     } 
    }); 

只要用戶輸入在文本框中的一個關鍵,一個AJAX調用到PHP文件進行。這個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); 

    } 
?> 

出於某種原因,自動完成不工作我 - 我究竟做錯了什麼?

回答

2

在PHP中,您嘗試使用$_GET['term'],但在JavaScript中,您的變量名爲input。更改要使用的數據對象term而不是input

data: { 
    term: request.term 
},