2017-02-13 16 views
0

json配列をajaxから取得しようとしましたが、テキストファイルに書き込むときに何も表示されません。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呼び出しのdeletefileは空になり、設定もされていないので、.phpを変更してみてくださいdeletefile = true – dsadnick

+1

'$ jsondata = json_decode(file_get_contents( 'php:// input'))' – Scuzzy

+1

... $ _GET ['deletefile'] 'はURL行にあるので、まだ入力されていなければなりません。 – Scuzzy

答えて

1

$_POSTにはキーと値のペアが含まれ、送信するものは文字列です。

標準入力を読むか、実際にキーと値のペアを送信する必要があります。

最初のケースはすでに@Scuzzyによってコメントとして投稿されています。

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

とPHPで:標準のキーと値のペアを使用して、後者の場合

$_POST

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では、あなたは、ファイルに書き込むことができる文字列に$_POST配列を変換するためにjson_encode()を使用する必要があります。あなたのアヤックスそれはPOSTの種類で電話している場合(ISSET($ _ POST [ '' DELETEFILE])){} PHPはそれをGET探していること するためにPHPを変更 で

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

ありがとうございます! –

関連する問題