[英]JSON response from php on AJAX call
I am doing a ajax call from java script and Im trying to get json response from php, if I set dataType as JSON, ajax error block is getting executed if not success block is getting executed, without specifying dataType if I try to console.log the response in success block I am getting nothing我正在从 Java 脚本执行 ajax 调用,并且我试图从 php 获取 json 响应,如果我将 dataType 设置为 JSON,如果没有执行成功块,则会执行 ajax 错误块,如果我尝试 console.log,则不指定 dataType成功块中的响应我什么也没得到
JS JS
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 PHP
<?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);
please help me figure out how to get json response to an ajax call in PHP请帮我弄清楚如何在 PHP 中获得对 ajax 调用的 json 响应
contentType: "application/json",
contentType: "application/json",
JS File: JS文件:
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);
}
});
PHP File: PHP文件:
<?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);
}
?>
从您的 JS 代码中删除contentType: "application/json"
,并在 PHP 文件中正确关闭大括号,它会正常工作。
You can convert the PHP array in JSON format with json_encode() function and return as a response.您可以使用 json_encode() 函数将 PHP 数组转换为 JSON 格式并作为响应返回。 Set dataType: 'JSON' when send AJAX request.
发送 AJAX 请求时设置 dataType: 'JSON'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.