2017-02-13 85 views
0

試圖從ajax獲取json數組,但是當我試圖在文本文件中寫下它時,它什麼也沒有顯示。PHP沒有得到AJAX JSON數據

var img = JSON.parse(localStorage.getItem("iPath")); 
       var img = JSON.stringify(img); 
       console.log(img); 

       $.ajax({ 
        url: './php/temporary.php?deletefile', 
        cache: false, 
        type: 'POST', 
        data: img, 
        success: function(respond, textStatus, jqXHR){ 

         if(typeof respond.error === 'undefined'){ 
          //window.location.assign("/buyplace.html"); 
         } 
         else{ 
          console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error); 
         } 
        }, 
        error: function(jqXHR, textStatus, errorThrown){ 
         console.log('ОШИБКИ AJAX запроса: ' + textStatus); 
        } 
       }); 

if(isset($_GET['deletefile'])){ 
     $params = json_decode($_POST); 
     $myfile = fopen("testfile.txt", "w"); 
     fwrite($myfile, $params); 
     //$img = "uploads/" . $imgPath; 
     //move_uploaded_file($imgPath, "./uploads/"); 
     //unlink('./uploads/' . $img); 
    } 
    ?> 

我該如何解決這個問題?

+1

在你的AJAX調用是POST的類型和PHP正在尋找它的GET php的改變 如果(isset($ _ POST [ '' DELETEFILE])){}。您的ajax調用中的deletefile將變爲空且未設置也嘗試更改.php?deletefile = true – dsadnick

+1

您可能需要使用'$ jsondata = json_decode(file_get_contents('php:// input'))' – Scuzzy

+1

... $ _GET ['deletefile']'在URL行上,所以它仍然應該被填充。 – Scuzzy

回答

1

$_POST將包含鍵值對,並且您發送的是一個字符串。

因此,您應該閱讀標準輸入,或者您需要確保您實際上正在發送鍵值對。

第一個案件已發佈爲@Scuzzy的評論。

對於後者,使用標準的鍵值對在$_POST

$.ajax({ 
     url: './php/temporary.php?deletefile', 
     cache: false, 
     type: 'POST', 
     data: {json: img}, 
     // the rest of your js 

而且在PHP中:

if(isset($_GET['deletefile'])){ 
    $params = json_decode($_POST['json']); 
    // the rest of your php 
+0

仍然沒有在文件中 –

+0

@VitoMotorsport有很多應該發生在你調用你的JavaScript和PHP寫入文件之間。你需要縮小問題的範圍。 – jeroen

0

有沒有需要發送的參數JSON。您可以使用對象作爲data:選項,並且每個屬性將作爲相應的$_POST元素髮送。

var img = JSON.parse(localStorage.getItem("iPath")); 
console.log(img); 

$.ajax({ 
    url: './php/temporary.php?deletefile', 
    cache: false, 
    type: 'POST', 
    data: img, 
    success: function(respond, textStatus, jqXHR){ 
     if(typeof respond.error === 'undefined'){ 
      //window.location.assign("/buyplace.html"); 
     } 
     else{ 
      console.log('ОШИБКИ ОТВЕТА сервера: ' + respond.error); 
     } 
    }, 
    error: function(jqXHR, textStatus, errorThrown){ 
     console.log('ОШИБКИ AJAX запроса: ' + textStatus); 
    } 
}); 

在PHP中,你需要使用json_encode()$_POST數組轉換爲可以寫入到一個文件中的字符串。

if(isset($_GET['deletefile'])){ 
    $params = $_POST; 
    $myfile = fopen("testfile.txt", "w"); 
    fwrite($myfile, json_encode($params)); 
} 
+0

非常感謝! –