我有 PHP 函数:
public function doit()
{
$arr1= array();
$arr1['index1'] = 'value1';
$arr1['index2'] = 'value2';
}
我从 JQuery 函数中调用它:
$.ajax
({
url: "/controller/doit",
success: function()
{
alert('done!');
}
});
我想要的就是 - 我的 JQuery 函数(包含这个 ajax 调用)将返回一个数组,该数组与 PHP 函数返回的数组相同(唯一的区别当然是语言:JS 而不是 PHP)
最佳答案
您需要从 doit 函数返回一些内容。
public function doit()
{
$arr1= array();
$arr1['index1'] = 'value1';
$arr1['index2'] = 'value2';
echo json_encode($arr1);
}
$.ajax
({
url: "/controller/doit",
success: function(data)
{
console.log(data);
}
});
编辑:
Jquery 到 PHP:当 JavaScript 运行时,它将使用 url 将数据数组发送到服务器。服务器接收数组,将其编码为 json 并将其发送回成功回调函数,该函数将数据记录到控制台。
// YOUR JAVASCRIPT FILE
// your data to send.
var data = {'index1': 'value1', 'index2': 'value2'};
$.ajax({
type: 'POST',
url: '/controller/doit',
data: data,
success: function(data) { console.log(data) },
dataType: 'json'
});
//YOUR PHP FILE
public function doit()
{
// you should be setting your content type header to application/json if sending json
header('Content-type: application/json');
echo json_encode($_POST['data']);
}
关于php - 如何解码从 php 到 jquery ajax 的数组响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676171/