我已经用一个固定的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文件并打印出来,那就更好了。如果这个问题用词不正确或者很基本,我很抱歉。另外,请慢慢来,解释一下代码。
发布于 2015-07-22 00:04:57
需要添加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
https://stackoverflow.com/questions/31543792
复制相似问题