从php数组自动完成

Sin*_*uri 5 javascript php arrays autocomplete

我写了这段代码从php数组做自动完成,但它没有用,有人可以帮忙吗?

php数组

$cars = array("Volvo", "BMW", "Toyota");
Run Code Online (Sandbox Code Playgroud)

我的表格

<form id="frm" method="post">
<input id="cartag" type="text" name="car">
</form>
Run Code Online (Sandbox Code Playgroud)

脚本

$(function() {
var availableTags = [ <?php echo implode(',',$cars); ?>];
	$( "#cartag" ).autocomplete({
	source: availableTags
	});
});
Run Code Online (Sandbox Code Playgroud)

PHP*_*... 7

如果你想在jQuery中使用php数组,你必须使用json_encode.

像这样:

var availableTags =  <?php echo json_encode($cars); ?>;
Run Code Online (Sandbox Code Playgroud)

工作演示:

<?php

$cars = array("Volvo", "BMW", "Toyota");

?>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<form id="frm" method="post">
<input id="cartag" type="text" name="car">
</form>
<script>

$(function() {
var availableTags =  <?php echo json_encode($cars); ?>;
    $( "#cartag" ).autocomplete({
    source: availableTags
    });
});

</script>
Run Code Online (Sandbox Code Playgroud)