我正在使用以下代码将表单中的数据发送到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
,但没有任何效果。
我做错了什么?
答案 0 :(得分:4)
从评论中听起来你使用的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');
}
});
答案 1 :(得分:0)
用于解析,使用jQuery.parseJSON(returnedData);
答案 2 :(得分:0)
在你的ajax调用中添加dataType。
$.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');
}
});