简体   繁体   中英

Returning an array from a PHP function to jQuery

I have a PHP 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) . ';'
?>

我回应jkndrkn和Wookai所说的,但我想补充一点,如果你没有使用ajax,你仍然可以使用json_encode()将数组直接插入你的javascript / jquery代码中。

使用json_encode()将其编码为JSON,将其打印到页面,然后使用jQuery调用此页面例如使用$ .get() )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM