我已经使用 json 和 php 自动完成。它有效,但现在我需要从 json 中获取第二个数组。
这是我在 source.php 上的脚本
<?php
$req = "SELECT namaBarang, harga FROM masternamabarang WHERE namaBarang LIKE '%".$_REQUEST['term']."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = array('label' => $row['namaBarang'],'harga' => $row['harga']);
}
echo json_encode($results);
?>
以及 autocomplate.php 的脚本
<html>
<head>
<script src="js/jquery-1.9.1.js"></script>
<script src="json/js/jquery-ui-1.10.3.js"></script>
<script>
$(function()
{
$( "#NAMA" ).autocomplete({
source: 'source.php'
});
});
</script>
<script>
function ambil()
{
var x = document.getElementById('NAMA').value;
document.getElementById('HARGA').value=x;
}
</script>
</head>
<body>
<form>
<input type="text" name="NAMA" size="50" id="NAMA" onchange="ambil()"/><br>
<input type="text" name="HARGA" size="50" id="HARGA" />
</form>
</body>
自动完成功能运行良好,但我需要的只是从 JSON 数组中取出第二个数组 [HARGA] 并将其填充到文本框 HARGA 中。
感谢您的回答。
最佳答案
你的 script.php 工作正常。它给你 json 结果类似
[{"label":"laba","value":"vala"},{"label":"labb","value":"valb"}]
您可以像这样在浏览器中记录(javascript)结果
console.log(data[0].value); // array index 0 for first row, you can try 1,2 etc...
您可能需要select方法来绑定(bind)所选内容:
$( "#search" ).autocomplete({
source: data,
select: function( event, ui ) {
console.log(ui); // log selected data row
$('#mySelectedInput').val(ui.item.value); // bind value wherever you like
}
});
资源
http://api.jqueryui.com/autocomplete/#event-select
http://jqueryui.com/autocomplete/#custom-data
关于javascript - 如何获取json中的第二个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20875212/