我使用PHP和MySQL来换掉一些内容。 Click处理程序向执行查询的PHP脚本发送AJAX请求,然后将结果编码并打印为JSON对象。
所有这一切似乎都有效,但我似乎陷入了最愚蠢的事情: 我无法弄清楚如何实际使用结果,就像将各个值设置为JavaScript变量一样。
编辑:我添加了一些我试过的东西,以获得打印到控制台的特定值,到目前为止没有运气。
编辑:找到正确的语法:
response[0].foo
的javascript:
var listId = $(this).children('.hidden-id').html();
var options = new Object();
options.data = listId;
options.dataType = 'json';
options.type = 'POST';
options.success = function(response) {
console.log(response[0].foo);
};
options.url = './inc/change_list.php';
$.ajax(options);
PHP脚本:
$list_id = $_POST['list_id'];
$q = "SELECT id, title, description, position FROM items WHERE list_id=$list_id ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
$result = array();
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$add_result = [
'id' => $row['id'],
'title' => $row['title'],
'description' => $row['description']
];
$result[] = $add_result;
}
$result = json_encode($result);
echo $result;
} else {
echo '{"result":"failure"}';
}
答案 0 :(得分:-3)
JSON响应将自动解析为Javascript对象。所以你可以这样做:
options.success = function(response) {
console.log(response.foo); // logs "bar"
// or
var foo = response.foo; // foo now holds "bar" as it's value
};