2017-05-09 72 views
0

我正在做一個來自java腳本的ajax調用,並試圖從PHP獲得json響應,如果我將dataType設置爲JSON,如果不成功塊正在執行,ajax錯誤塊得到執行,沒有指定的dataType如果我嘗試在CONSOLE.LOG成功塊,我得到什麼響應來自php的AJAX調用的JSON響應

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 
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); 

請幫我找出如何獲得JSON響應PHP

+1

您確定您正在調用正確的URL **'../../../../PHP/adminScripts/addNewTrack.php'** –

+0

任何控制檯錯誤? – madalinivascu

+0

可以嘗試刪除ajax中的contentType,然後有'dataType:「json」,encode:true,'然後刪除php中的標頭 –

回答

1
  • 在您的JS文件的AJAX調用,請刪除contentType: "application/json",
  • 在你的PHP文件中,檢查「包含文件的URL」和
  • 關閉if語句塊正常

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文件:

<?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); 
    } 
?> 
0

從您的JS代碼刪除contentType: "application/json",並在PHP文件正確地關閉括號,它會正常工作。

+0

謝謝,它的工作正常:) –