我已经做了大量的阅读研究,试图弄清楚为什么ajax正在读取未定义的json响应,当然我也尝试了很多这些解决方案,但不幸的是它们对我不起作用。如果你们可以提供帮助,那就太棒了!!!!
我尝试使用data.status和data ['status']添加dataType:'json',它们仍然是未定义的。我可以看到php以json格式响应正确的状态(响应的一个示例位于页面底部)
php方面:
//doing sql query
if ($conn->query($sql) === TRUE) {
$response_array["status"] = "success";
} elseif ($conn->errno == 1062) {
$response_array["status"] = "dup";
} else {
$response_array["status"] = "error";
}
header('Content-Type: application/json');
echo json_encode($response_array);
jquery方面:
$(document).ready( function(){
$('#name_form').submit( function(event) {
if ( !formValidation()) {
event.preventDefault();
} else {
var datastr = $('#addclass_form').serialize();
$.ajax({
type: 'POST',
url: someurl,
data: datastr,
success: function(data) {
alert(data.status);
console.log(data);
},
error: function() {
alert('php error');
}
});
}
});
});
html方:
<form id='name_form'>
<div>
<b>Class Name</b>
<input type='text' name='classname' id='classname' placeholder='Enter Class Name'>
</div>
<div class='ui-grid-c'>
<div class='ui-block-a main'><b>Component</b></div>
<div class='ui-block-b point'><b>Max Point</b></div>
<div class='ui-block-c per'><b>Percentage</b></div>
</div>
<div id='components'>
<div class='ui-grid-c'>
<div class='ui-block-a main'><input type='text' name='component0' id='component0' placeholder='Component'></div>
<div class='ui-block-b point'><input type='number' name='point0' id='point0' placeholder='Max Point'></div>
<div class='ui-block-c per'><input type='number' name='percentage0' id='percentage0' placeholder='Percentage'></div>
<div class='ui-block-d rm'><button type='button' class='ui-btn ui-icon-delete ui-shadow ui-corner-all ui-btn-icon-notext' disabled></button></div>
</div>
</div>
<br>
<input type='hidden' name='compSize' id='compSize'>
<input type='submit' class='ui-btn ui-btn-b ui-shadow ui-corner-all' value='Create Class'>
</form>
console.log(数据)的输出:
<!doctype html>
<html>
<head>
</head>
<body>
{"status":"success"}
</body>
</html>