PHP没有得到AJAX JSON数据

问题描述:

试图从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

$_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

有没有需要发送的参数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

非常感谢! –