2014-01-06 34 views
4

我正在从我的页面收集一些数据,将数据存储在数组中以便在页面上多次使用,并通过AJAX发送数组副本,将数据存储在数据库中一个PHP页面。数据我存储在阵列中的打破JSON的HTML字符串( )

其中一幅是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":""} 

看来&nbsp;以某种方式破坏了我的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 
} 

这是萤火虫说:

enter image description here

+0

什么事情'的var_dump($ _ POST [ 'post_data'])'说明了什么?看看JSON在那里发生了什么变化。如果是这样,那么你的jQuery代码中的东西是在客户端 –

+0

@MarcB,感谢您的帮助,但现在感谢Qunetin解决了。喜欢使用'mangled'和'mangling':) – TheCarver

回答

7

您正在将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 
}, 
+0

从已经秃顶的头上拉出更多的头发。为什么我没有想到这个?谢谢,昆汀。 +1的响应时间。 – TheCarver