Returning an array from a PHP function to jQuery
I have a PHP 开发者_JAVA技巧function that returns an array. What is the best way to "receive" this using jQuery?
Use json_encode() to turn your PHP array into a native JavaScript array, then use jQuery $.post, $.get, or $.ajax methods to fetch this value from your PHP script. I generally use $.post unless I need the special features that $.ajax provides.
I use smarty, and this is how I do it:
<?php
$smarty = new Smarty;
$array = array('foo' => 'bar', 'bar' => 'foo');
$smarty->assign('array', $array);
$smarty->display('template.htm');
?>
template.htm:
<html>
<head>
<script type="text/javascript">
var array = {$array|@json_encode};
</script>
</head>
<body>
</body>
</html>
If you don't use smarty you can do something like this:
<?php
$array = array('foo' => 'bar', 'bar' => 'foo');
echo 'var array = ' . json_encode($array) . ';'
?>
I echo what jkndrkn and Wookai said, but I would add that if you're not using ajax, you can still use json_encode() to insert the array directly into your javascript/jquery code.
Encode it in JSON using json_encode(), print it to the page and then call this page using jQuery (with $.get() for example).
精彩评论