简体   繁体   中英

Getting JSON in PHP from jQuery .ajax()

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:

var noteData =  { 
    nData: {
        "postID": $postID,
        "commentPar": $commentPar,
        "commentValue": $commentValue
    } 
}
var sendData = JSON.stringify(noteData);

$.ajax({
    type: "POST",
    url: templateUrl+"/addnote.php",
    data: sendData,
    dataType : 'json',
    success: function(data) { 
        alert(data);
        console.log(sendData);
    },
    error: function(e) {
        console.log(e.message);
        console.log(noteData);
        console.log(sendData);
        alert("error");
    }
});

Here is how I just test if the data is even being passed to PHP, it always returns back null .

<?php
  $nData = json_decode($_POST['nData']);
  echo json_encode($nData);
?>

What am I doing wrong?

You are sending the data as raw JSON to PHP, not as POST parameter.

There are two alternatives. The first one leaves your PHP intact:

var noteData =  { 
    nData: {
        "postID": $postID,
        "commentPar": $commentPar,
        "commentValue": $commentValue
    } 
}
var sendData = JSON.stringify(noteData);

$.ajax({
    type: "POST",
    url: templateUrl+"/addnote.php",
    data: {
        nData: sendData
    },
    dataType : 'json',
    success: function(data) { 
        alert(data);
        console.log(sendData);
    },
    error: function(e) {
        console.log(e.message);
        console.log(noteData);
        console.log(sendData);
        alert("error");
    }
});

The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.

<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);

This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers .

告诉你的帖子请求你发送json对象contentType:“application / json”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM