gpt4 book ai didi

javascript - HTML 字符串 ( ) 破坏 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:05:33 26 4
gpt4 key购买 nike

我从我的页面收集一些数据,将数据存储在一个数组中以在页面上多次使用,然后通过 AJAX 发送数组的副本,将数据存储在 PHP 页面上的数据库中。

我存储在数组中的一条数据是 TinyMCE 所见即所得编辑器的输出,因此它包含 HTML,但我刚刚发现这是一个问题 - 我将解释:

在我的所见即所得编辑器中输入一行文本并触发我的 AJAX 事件后,这是我的控制台中显示的 JSON 字符串,一切正常,数据库已发送并存储:

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>","keywords":""}

如果我写两行文本,这是 JSON 字符串并且是成功的:

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdg.</p>\n<p>fgfgfdg</p>","keywords":""}

现在,如果我写了一行文本并按回车键而不在第二行输入任何内容,我将得到以下失败的结果。

{"id":"229","topic":"","title":"","description":"","content":"<p>fgfgfdgdfgdfgdfgdfg.</p>\n<p>&nbsp;</p>","keywords":""}

  似乎以某种方式破坏了我的 JSON 输出。我的 PHP 无法访问解码后的数组值,因为没有数组。 print_r(json_decode($json)) 不返回任何内容。有人可以帮忙吗?

这是我使用 jQuery 的 HTML 页面:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<script>
var post_data = {};

post_data.id = post_id;
post_data.topic = topic;
post_data.title = title;
post_data.description = description;
post_data.content = tinyMCE.activeEditor.getContent();
post_data.keywords = keywords;

post_data = JSON.stringify(post_data);

save_post_request = $.ajax({
url: 'ajax/save-post.php',
type: 'POST',
data: "save_mode="+save_mode+"&post_data="+post_data,
dataType: 'text',
cache: false
});
</script>

这是我的 PHP 页面:

header('Content-type: application/json; charset=UTF-8');

$post_data = isset($_POST['post_data']) ? $_POST['post_data'] : null;
$post_data_arr = json_decode($post_data, true);
$post_id = $post_data_arr['id'];
$topic = $post_data_arr['topic'];
// others
$content = $post_data_arr['content'];

if (!$post_data_arr['id']) {
// fails here
// id is not accessible when the JSON contains <p>&nbsp;</p> in the 'content' item
}

Firebug 是这么说的:

enter image description here

最佳答案

您将 JSON 放入一些 URL 编码数据中,但您并未对其进行 URL 编码。

& 字符在 URL 编码数据中具有特殊含义(它分隔键/值对),因此这意味着您正在破坏数据。

在将数据添加到字符串之前,使用 encodeURIComponent 函数对您的数据进行正确编码:

data: "save_mode="+encodeURIComponent(save_mode)+"&post_data="+encodeURIComponent(post_data),

但是,由于您使用的是 jQuery,因此您不应该首先手动构建 URL 编码数据。 jQuery 可以为你做这件事。向 data 传递一个对象而不是字符串:

data: {
save_mode: save_mode,
post_data: post_data
},

关于javascript - HTML 字符串 ( ) 破坏 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20960582/

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