我正在从java脚本进行ajax调用,我试图从php获取json响应,如果我将dataType设置为JSON,如果没有成功块执行则会执行ajax错误块,如果我尝试不指定dataType console.log成功块中的响应我什么都没得到
JS
return (self.user + self.status + self.image_id)
PHP
let CurrentDate = Date();
console.log(CurrentDate);
jsonObject = {
'TrackName' : 'Material Science',
'TrackDesc' : 'Test Text Test Text Test Text Test Text Test Text Test Text Test Text ',
'Timestamp' : CurrentDate
}
console.log(jsonObject);
$.ajax({
type:'post',
url:'../../../../PHP/adminScripts/addNewTrack.php',
contentType: "application/json",
data: {trackDetails:jsonObject},
dataType: "json",
success: function(response) {
console.log('SUCCESS BLOCK');
console.log(response);
},
error: function(response) {
console.log('ERROR BLOCK');
console.log(response);
}
});
请帮我弄清楚如何在PHP中使用json响应ajax调用
答案 0 :(得分:1)
let CurrentDate = Date();
jsonObject = {
'TrackName' : 'Material Science',
'TrackDesc' : 'Test Text Test Text Test Text Test Text Test Text Test Text Test Text ',
'Timestamp' : CurrentDate
}
$.ajax({
type:'post',
url:'addNewTrack.php',
data: {trackDetails:jsonObject},
dataType: "json",
success: function(response) {
console.log('SUCCESS BLOCK');
console.log(response);
},
error: function(response) {
console.log('ERROR BLOCK');
console.log(response);
}
});
JS文件:
<?php
header('Content-type: application/json');
include('../connection.php');
if($_POST) {
$obj = $_POST['trackDetails'];
$TrackName = mysql_real_escape_string($obj['TrackName']);
$TrackDesc = mysql_real_escape_string($obj['TrackDesc']);
$TrackAdderID = 'Admin '; //$_SESSION["userID"];
$Timestamp = mysql_real_escape_string($obj['Timestamp']);
$response_array['status'] = 'status123';
echo json_encode($response_array);
}
?>
PHP文件:
let btnImage = UIImage(named: "checkmarkWhite")
categoryButtonOne.setImage(btnImage, forState: UIControlState.Selected)
categoryButtonOne.semanticContentAttribute = .ForceRightToLeft
categoryButtonOne.imageEdgeInsets = UIEdgeInsetsMake(0, (categoryButtonOne.frame.width / 2) - (btnImage?.size.width)! - 10, 0, 0)
答案 1 :(得分:0)
从JS代码中删除contentType: "application/json"
,并在PHP文件中正确关闭大括号,它将正常工作。
答案 2 :(得分:0)
您可以使用json_encode()函数将JSON格式的PHP数组转换为响应。发送AJAX请求时将dataType设置为“ JSON”。