2013-07-20 141 views
0

我正在返回一個JSON編碼數組:echo(json_encode($data));來自php,我希望它從JQuery自動填充中填充提示框。我正在使用:JQuery自動完成,使用來自pHp json的數據填充

$("#field").autocomplete({ 
      source : "SearchTest.php", 
      maxLength: 5 
     }); 

不知道爲什麼這不起作用。在每次按鍵之後,我都會檢索數據,並用該數據填充提示框,我不希望自動完成對我進行排序和選擇,我正在執行該服務器端。現在只是一個字符串列表。能夠自定義數據的呈現方式也不錯。

編輯:修改後的源發佈:

$("#field").autocomplete({ 
      source : function(request, response) { 
       $.post("SearchTest.php", request, response); 
      }, 
      maxLength : 5 
     }); 

現在收到此錯誤:

Uncaught TypeError: Cannot use 'in' operator to search for '1240' in 
Notice: Undefined index: field in /.../SearchTest.php on line 25 

第25行是:$whatTheyWantToSearch = $_POST['field'];

+0

你會得到什麼錯誤?你可以粘貼你的PHP代碼,你的JS代碼似乎是好的。 – m4t1t0

+0

沒有錯誤。我只是意識到我沒有發送任何東西到SearchTest.php。我如何發佈到服務器並檢索JSON來填充自動填充? – John

+0

你能告訴我你的php代碼嗎? – m4t1t0

回答

3

嘗試使用ajax

var searchRequest = null; 
$("#field").autocomplete({ 
    maxLength: 5, 
    source: function(request, response) { 
     if (searchRequest !== null) { 
      searchRequest.abort(); 
     } 
     searchRequest = $.ajax({ 
      url: 'SearchTest.php', 
      method: 'post', 
      dataType: "json", 
      data: {term: request.term}, 
      success: function(data) { 
       searchRequest = null; 
       response($.map(data.items, function(item) { 
        return { 
         value: item.name, 
         label: item.name 
        }; 
       })); 
      } 
     }).fail(function() { 
      searchRequest = null; 
     }); 
    } 
}); 

JSON響應示例中SearchTest.php

<?php 
header('Content-type: application/json'); 
echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}'; 
?> 

Demo Fiddle

Remote JSONP Demo

+0

沒有工作.... – John

+0

保持去.fail函數 – John

+0

這意味着響應不是從SearchTest.php正確的'JSON'格式,回答更新,添加'​​方法:'後',' 'JSON'格式和Demo Fiddle –

1

此適當的JSON格式從PHP:

<?php 
    echo '[ {"name1":"val1"},{"name2":"val2"} ]'; 
?> 

從JS至極指[] -array {}對象。

在我來說,我autocomlete widjet這工作得很好:

$response="["; 
    while($row = $res->fetch_assoc()){ 
     if($response !="[")$response.=","; 
     $response.='{"label":"'.$row["fio"].'","value":"'.$row["id"].'"}'; 
    } 
    $response.="]"; 

    echo $response; 
0

財產以後這樣是最好的方式。 json_encode爲你做的一切工作。

$result = $_mysqli->query(...); 
    $rs = array(); 
    $pos = 0; 
    while($row = $result->fetch_assoc()){ 
     $rs[$pos]["n1"] = $row["n1"]; 
     $rs[$pos]["n2"] = $row["n2"]; 
     ... 
     $rs[$pos++]["nn"] = $row["nn"]; 

    } 
    header('Content-type: application/json'); 
    echo json_encode($rs);