我使用以下一段代码将数据从表单发送到php脚本,该脚本将使用类进行一些计算:
$.ajax({
type: "POST",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
我的PHP脚本创建一个数组,我用JSON编码然后回显
$jsonString = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
echo json_encode($jsonString);
目前为止,一切都好。但我不太热衷于显示原始 JSON。我想在将文本写入文档之前对其进行格式化。我试过$.parseJSON()
和$.getJSON()
,但没有一个有效。jQuery文档说它需要一个字符串,但json_encode()
不是让我的数组变成字符串吗?echo
不是把它变成一根绳子吗?为什么我的jQuery文件中出现错误Uncaught SyntaxError: Unexpected token {
?我的理论是它周围没有单引号。
我尝试在我的PHP脚本中使用header('Content-type: application/json')
,我也在我的AJAX POST中尝试过dataType: json
,但没有任何效果。
我做错了什么?
从评论中听起来你用错json_encode。将每条数据存储到一个数组中,然后对数组进行编码。
$data = array();
for($i=0;$i<$something;$++) {
$data[] = array(
'monthText' => $Month->getMonthText($month),
'gross' => $formatGross,
'net' => $formatNet
);
}
echo json_encode($data);
那么你的Javascript需要
$.ajax({
type: "POST",
url: "test2.php",
dataType:"json",
data: values,
success: function(returnedData) {
//returnedData will now be an array Object
for( var i=0; i<returnedData.length; i++ ) {
$("#result").html(returnedData[i].monthText);
}
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});
对于解析,请使用 jQuery.parseJSON(返回数据);
像这样在 ajax 调用中添加数据类型。
$.ajax({
type: "POST",
dataType:"json",
url: "test2.php",
data: values,
success: function(returnedData) {
$("#result").html(returnedData);
},
error: function(){
alert("failure");
$("#result").html('error while submitting');
}
});