Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

send json object from javascript to php

I am trying to send JSON object from Javascript/Jquery to PHP and I am getting and error msg in my console. What am I doing wrong. I am new to JS and PHP.

JQuery file:

$(document).ready(function() {
    var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
    // console.log(typeof(flickr));
    var makeFlickrCall = function(flickrObj){
        $.ajax({
            url: '../phpincl/apiConnect.php',
            type: 'POST',
            data: flickrObj
        })
        .done(function(data) {
            console.log("success");
            console.log(JSON.stringify(data));
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
    };

    makeFlickrCall(flickr);
});

PHP file

<?php       
    $obj = $_POST['data'];
    // print_r($obj);
    return $obj;
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The standard jQuery .ajax() method uses the data property to create an x-www-form-urlencoded string to pass in the request body. Something like this

action=Flickr&get=getPublicPhotos

Therefore, your PHP script should not look for $_POST['data'] but instead, $_POST['action'] and $_POST['get'].

If you want to send a raw JSON data payload to PHP, then do the following...

Set the AJAX contentType parameter to application/json and send a stringified version of your JSON object as the data payload, eg

$.ajax({
    url: '../phpincl/apiConnect.php',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(flickrObj),
    dataType: 'json'
})

Your PHP script would then read the data payload from the php://input stream, eg

$json = file_get_contents('php://input');

You can then parse this into a PHP object or array...

$dataObject = json_decode($json);
$dataArray = json_decode($json, true);

And, if you're just wanting to echo it back to the client..

header('Content-type: application/json');

// unmodified
echo $json;

// or if you've made changes to say $dataArray
echo json_encode($dataArray);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...