【发布时间】:2019-08-09 14:47:10
【问题描述】:
我正在尝试通过 json 发送 foreach 循环,然后使用 innerHTML 显示。没有任何错误。我遇到的问题是输出是显示:
[对象对象]
而不是 foreach 循环中的内容。
如何让输出成为foreach 循环内的$html 行?
try {
$sql_recentProjects = "
SELECT *
FROM project_gallery
ORDER BY date_added ASC
LIMIT 5
";
if ($recentProjects_stmt = $con->prepare($sql_recentProjects)) {
$recentProjects_stmt->execute();
$recentProjects_rows = $recentProjects_stmt->fetchAll(PDO::FETCH_ASSOC);
$recProj_arr = array();
foreach ($recentProjects_rows as $recentProjects_row) {
$precProjName = $recentProjects_row['p_name'];
$recProjImg = $recentProjects_row['p_img'];
//$project_img = substr($project_img, 2);
$displayRecProjImg = '<img src="/php'.$recProjImg.'" alt="'. $precProjAlt .'" class="projectDisplayImg">';
$html = '';
$html .= '<div class="recentProjectCont">';
$html .= '<div class="recentProjectImg">';
$html .= $displayRecProjImg;
$html .= '</div>';
$html .= '<div class="recProjInfoCont">';
$html .= '<div class="">';
$html .= $precProjName;
$html .= '</div>';
$html .= '</div>';
$html .= '</div>';
$recentProjData = array('html' => $html);
//$proj_arr[] = $data;
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['recentProjectData' => $recentProjData]);
JS
function ajaxCallCatalogs() {
$.ajax({
url: 'php/projects/projectGallerySelect.php',
datatype: 'json',
success: function (data) {
//console.log(data);
obj = JSON.parse(data);
recentProjectData = obj.recentProjectData; //Recent 5 Projects submitted to gallery
document.getElementById('recentProjectWrap').innerHTML = recentProjectData;
}
});
}
ajaxCallCatalogs();
setInterval(ajaxCallCatalogs, 150000);
【问题讨论】:
-
因为你有
$recentProjData = array('html' => $html)。所以recentProjectData是一个带有html元素的对象 -
你为什么不只是发送 html 字符串而不是尝试作为 json 发送?
-
如果你去掉评论,看看你收到的数据的结构://console.log(data);
-
document.getElementById('recentProjectWrap').innerHTML = recentProjectData.html;或document.getElementById('recentProjectWrap').innerHTML = recentProjectData['html']; -
作为答案发布...
标签: javascript php arrays json ajax