【发布时间】:2023-03-24 14:17:02
【问题描述】:
尝试将 php 中的 json_encode 变量传递给 javascript。在 javascript 中得到一个未捕获的错误。以前可以用,什么都没改,现在不行了?!?
JSON 变量适用于 PHP。在php中尝试print_r,OK。浏览器网络也可以。
我想在 PHP 中传递的变量:
$response['id'] = $id;
$response['name'] = $name;
$response['note'] = $note;
$response['image'] = $image;
$response['bumbu'] = $bumbu;
$response['banyak'] = $banyak;
$response['masak'] = $masak;
$response['images'] = $images;
print_r($response);
json_encode($response);
我的javascript:
$('#viewResep')
.on('show.bs.modal', function (e) {
var id = $(e.relatedTarget)
.data('id');
console.log('Requested : ' + id);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("demo").innerHTML = this.getAllResponseHeaders();
}
};
xhttp.open('GET', 'process_post.php?view=' + id, true);
xhttp.send();
fetch('process_post.php?view=' + id)
.then(text => JSON.parse(text))
.then((data) => {
r_Name = data.name;
r_Note = data.note;
r_Image = data.image;
r_Bumbu = data.bumbu;
r_Banyak = data.banyak;
r_Masak = data.masak;
r_Images = data.images;
});
});
我想在我的 javascript 中使用 json_encode 获取所有变量
【问题讨论】:
-
您打印了
print_r输出,并丢弃了json_encode结果。删除print_r并将echo添加到下一行。 -
删除
print_r(),只删除echo json_encode($response); -
您不需要同时使用
XMLHttpRequest和fetch(),因为它们基本上都在做同样的事情。只需使用fetch(`process_post.php?view=${encodeURIComponent(id)}`).then(res => res.json()).then(data => { ... }) -
确保您的 PHP 脚本不输出
echo、print或以其他方式输出echo json_encode($response);以外的任何内容。目前,它看起来像是在打印一些 HTML。请查看问题顶部链接的重复项 -
你是对的菲尔!我不小心把 print_r 放在了上面的某个地方。现在它可以工作了,但不要将数组正确传递给 javascript。呸!
标签: javascript php json fetch