gpt4 book ai didi

javascript - 如何操作 json 数组中的每个项目以转到特定的元素类、href、id、文本等?

转载 作者:行者123 更新时间:2023-12-02 21:33:52 25 4
gpt4 key购买 nike

基本上,我单击一个 div,然后将 SQL 数据库中的数据添加到其各自的位置。我试图遍历数组中的每个项目并按照我的意愿操作它们。假设我要添加 task_date: "2020-03-01 21:44:55"到一个 href。并添加title: "asdfasdf"到 divs 类(当然结果在引号中)。这可能听起来很愚蠢,但我只需要知道,这样我就可以以我选择的任何方式自己完成。我知道这一切都可以使用 Jquery 完成,但是我如何遍历每个结果来单独操作它?我需要JSON.parse(response); ?或者更改我的 PHP 回显结果?
AJAX 调用

   $(function(){
$(".task-listing").click(function() {
$.ajax({
type: 'POST',
url: '/task-info-get.php',
dataType: 'json',
data: 'info=' + $(this).attr("id"),
success: function (response) {
//what i want:
$(".link").attr("href", response[0]);
$(".price").attr('class', response[1]);
}
})
});
});

PHP 文件

<?php
include 'sqlconnection.php';
$conn = OpenCon();

$stmt = $conn->prepare('SELECT task_date,title,description,location,price,startdate,tasktime FROM tasks WHERE pid='.$_POST['info']);
$stmt->execute();
$stmt->bind_result($task_date,$title,$description,$location,$price,$startdate,$tasktime);
while($stmt->fetch()) {
$output[]=array(
'task_date' => $task_date,
'title' => $title,
'description' => $description,
'location' => $location,
'price' => $price,
'startdate' => $startdate,
'tasktime' => $tasktime
);
}
$json=json_encode($output);
echo $json;

$stmt->close();
CloseCon($conn);
?>

控制台中的成功响应

task_date: "2020-03-01 21:44:55"
title: "asdfasdf"
description: "asdfasdf"
location: "Local"
price: 3333
startdate: "2020-03-18"
tasktime: "00:00:00"

最佳答案

请务必注意您的 $output 变量类型。您将其视为数组,并且在 while 循环内将数组作为数组元素添加到 $output 中。

您的代码:

$output[]=array(
'task_date' => $task_date,
'title' => $title,
'description' => $description,
'location' => $location,
'price' => $price,
'startdate' => $startdate,
'tasktime' => $tasktime
);

我假设你的愿望是:

$output=array(
'task_date' => $task_date,
'title' => $title,
'description' => $description,
'location' => $location,
'price' => $price,
'startdate' => $startdate,
'tasktime' => $tasktime
);

删除了两个字符。 []

接下来是你的 Javascript。您将响应视为索引数组(使用以 0 开头的数字键访问),而实际上它是关联数组(使用任意键访问)。

示例是:

 $(".price").attr('class', response[1]);

当所需的代码应该是:

 $(".price").attr('class', response['title']);

在不知道您的 HTML 结构的情况下,我无法为您提供 100% 有效的具体代码,但我希望这个建议至少能让您朝着正确的方向前进。如果您还提供 HTML 结构,则可以提供更多帮助。

题外话:这是我的第一个回答。多年来我一直从这个网站获得帮助,所以我认为现在是我开始回馈社会的时候了。如果您有任何礼仪建议或资源供我阅读以提高我的回答质量,请告诉我。谢谢。

关于javascript - 如何操作 json 数组中的每个项目以转到特定的元素类、href、id、文本等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com