[英]ajax and json object encode and decode into and from php script
我創建了一個帶有固定json對象的簡單html文件。 我想將對象帶到php文件text.php,對其進行編碼,解碼,將其打印在php文件中,然后再將其打印回html文件中。 html文件:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script>
var key=45;
var value=65;
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("text.php");
});
});
</script>
<div id="div1"><h6>Result</h6></div>
<button>Get External Content</button>
</body>
</html>
text.php代碼:
<?php
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true);
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
echo json_encode($rated_json);
}
?>
的
echo json_encode($rated_json);
在text.php的最后一行不起作用。 我不知道我們是否不能打印編碼的東西。 代替該行,即使我鍵入echo“ hello” ;,也不會在php文件中打印。 如果有任何方法可以在text.php中打印$ JSONArray變量,那將很棒。 如果我可以將json對象編碼在html文件本身中,發送到php腳本,在那里進行解碼,然后發送回並在html文件中打印,那將更好。 很抱歉,這個問題的措詞不正確或非常基礎。 另外,請慢一點並解釋代碼。
您需要添加contentType:“ application / json; charset = UTF-8”,
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
contentType: "application/json; charset=UTF-8",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
dataType選項僅用於解析接收到的數據。
如果仍然無法正常工作,請添加以下內容:processData:false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.