[英]JSON-encoded PHP array submitted in hidden field of form - gives weird output when printed out in page to which the form is submitted
在以下SSCCE中,在index.php
,將打印一個按鈕。 當您單擊此按鈕時,將提交一個form
(在JS中該button
的單擊偵聽button
中),該form
包含一個隱藏的input
字段,其值是json_encode($anArray)
。
表單的action
屬性具有值test.php
,因此將表單提交給test.php
。
在test.php
,我打印了$_POST
的內容,但是得到了這個奇怪的輸出:
Array ( [something] => { )
問題是為什么,該如何解決?
第二個問題是,目前test.php
在新選項卡中打開,我是否可以強制其在新窗口中打開?
test.php的:
<?php
if (isset($_POST["something"])) {
print_r( $_POST );
} else {
echo '$_POST["something"] is not set.';
}
?>
的script.js:
$(document).ready(function() {
$("#someButton").click(function() {
window.open('', 'TheWindow'); document.getElementById('TheForm').submit(); });
});
index.php文件:
<?php
$dataToPass = array(
"A" => array(
1 => array(
"id" => 1,
"secondId" => 2,
"thirdId" => 3
)
),
"B" => array(
1 => array(
"id" => 4,
"secondId" => 5,
"thirdId" => 6
),
2 => array(
"id" => 7,
"secondId" => 8,
"thirdId" => 9
)
),
"C" => array(
1 => array(
"id" => 10,
"secondId" => 11,
"thirdId" => 12
)
)
);
?>
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<?php
print_r(json_encode($dataToPass));echo "<br><br>";//check
?>
<button id="someButton">Click me</button>
<form id="TheForm" method="post" action="test.php" target="TheWindow">
<input type="hidden" name="something" value="<?php echo json_encode($dataToPass); ?>" />
</form>
</body>
</html>
您的<input>
標記應如下所示:
<input type="hidden" name="something" value='<?php echo json_encode($dataToPass); ?>' >
請注意,對於value
屬性,使用單引號而不是雙引號。 JSON字符串包含雙引號字符; 您的HTML正以如下形式到達瀏覽器:
<input type="hidden" name="something" value="{"A":..." />
這就是為什么您只獲得{
值的原因。
確實,要確定一切正常(JSON 也可以包含單引號),您應該使用HTML編碼器將所有嵌入的單引號或雙引號字符轉換為HTML實體。 這樣,您可以確保最終的HTML不會混淆HTML解析器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.