我有以下AJAX请求:
$(function(){
$("#MPrzezn").typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'test',
displayKey: 'value',
source: function(query, process){
$.ajax({
url: 'sprawdzKraj.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
console.log(data);
}
});
}
});
});
...以及后端的以下php:
<?php
require_once 'core/init.php';
$user = new User(); //current User
if($user->isLoggedIn()){
if(isset($_POST['query'])){
$query = $_POST['query'];
$delegacja = new Delegacja();
$dataListaDelegacji = $delegacja->listujMiasta($query);
header('Content-Type: application/json');
$json_response = json_encode($dataListaDelegacji);
echo $json_response;
}
} else {
$isLoggedIn = false;
$smarty->assign("userid","",true);
$smarty->assign("isLoggedIn",$isLoggedIn,true);
Redirect::to('login.php');
}
php脚本返回一个合适的json:
[{"ID":"66","IDKraju":"117","NazwaMiasta":"Inowroc\u0142aw","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"251","IDKraju":"117","NazwaMiasta":"\u015awinouj\u015bcie","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"2222","IDKraju":"74","NazwaMiasta":"Rhinow","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"3508","IDKraju":"94","NazwaMiasta":"San Bernardino","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null}]
下图显示了浏览器如何获取json:
There are 4 cities that match the query - each object is a city entry
我的目标是传递&#34; NazwaMiasta&#34;到了一个输入,但我得到了#34;未定义&#34;条目。我尝试了不同的东西,但它总是像这样显示未定义:
Red arrows show all 4 json nodes
我希望我能很好地描述我的问题。我知道我非常接近,但我自己找不到解决方案。我会感激任何帮助。
由于
答案 0 :(得分:0)
你必须正确displayKey
值!
投入:
displayKey: 'value',
设置:
displayKey: 'NazwaMiasta',
编辑:
详细说明:当您通过ajax调用返回数据时,typeahead
不知道要显示的值。因此,您必须设置该键的值的位置。您的返回数组对象具有如下结构:
['key1':'value1', 'key2':'value2',...]
通过设置ie 'key1'
,typeahead
知道如何访问值,即:
currentElement['key1']...
然后把这个值放到html。