本文介绍了将json对象从javascript发送到php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON对象从Javascript / Jquery发送到PHP,我在控制台中收到错误信息。我究竟做错了什么。我是JS和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文件:

$(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文件

<?php
    $obj = $_POST['data'];
    // print_r($obj);
    return $obj;
?>


推荐答案

Phil的优秀答案,但是因为OP标题说

Excellent answer by Phil, however since the OP title says

这是如何用(vanilla)javascript做的,以防它帮助有人寻找这种方法:

this is how to do it with (vanilla) javascript, in case it helps somebody looking for this method:

var jsondata;
var flickr = {'action': 'Flickr', 'get':'getPublicPhotos'};
var data = JSON.stringify(flickr);

var xhr = new XMLHttpRequest();
xhr.open("POST", "../phpincl/apiConnect.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // in case we reply back from server
        jsondata = JSON.parse(xhr.responseText);
        console.log(jsondata);
    }
}

注意我们还需要使用 JSON.parse()

将服务器的响应转换为javascript 对象现在,在服务器端(根据Phil的回答),如果您要向客户发送回复,您可以这样做:

Now, on the server side (based on Phil's answer) if you are sending back a response to the client, you could do:

header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;

注意

首先解码然后编码回原始json输入的原因是在数据中的(可能的)URL中正确地转义斜杠,例如

The reason behind decoding first and then encoding back the raw json input is to properly escape slashes in (possible) URLs within the data, e.g.

json_encode 将转换此网址

http://example.com

进入

http:\/\/example.com

...其中在OP中不是这种情况,但在其他一些情况下很有用。

... which is not the case in the OP but useful in some other scenarios.

这篇关于将json对象从javascript发送到php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 07:58