将 json 对象从 javascript 发送到 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23750661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:29:44  来源:igfitidea点击:

send json object from javascript to php

javascriptphpjqueryajaxjson

提问by Vish

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.

我正在尝试将 JSON 对象从 Javascript/Jquery 发送到 PHP,但我在控制台中收到错误消息。我究竟做错了什么。我是 JS 和 PHP 的新手。

JQuery file:

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 file

PHP文件

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

采纳答案by JFK

Excellent answer by Phil, however since the OP title says

Phil 的出色回答,但是因为 OP 标题说

send json object from javascript (not jQuery) to php

将 json 对象从 javascript(不是 jQuery)发送到 php

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

这是使用(香草)javascript 的方法,以防它帮助寻找此方法的人:

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);
    }
}

Noticewe still need to convert the server's response into a javascript objectusing JSON.parse()

请注意,我们还需要服务器的响应转换成JavaScript对象使用JSON.parse()

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

现在,在服务器端(基于 Phil 的回答),如果您要向客户端发回响应,您可以执行以下操作:

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;

NOTE:

注意

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

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

json_encodewill convert this URL

json_encode将转换此 URL

http://example.com

into

进入

http:\/\/example.com

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

...这在 OP 中并非如此,但在其他一些场景中很有用。

回答by Phil

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

标准的 jQuery.ajax()方法使用该data属性创建一个x-www-form-urlencoded字符串以传入请求正文。像这样的东西

action=Flickr&get=getPublicPhotos

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

因此,你的PHP脚本应该不找$_POST['data']而是$_POST['action']$_POST['get']

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

如果要将原始 JSON 数据负载发送到 PHP,请执行以下操作...

Set the AJAX contentTypeparameter to application/jsonand send a stringifiedversion of your JSON object as the datapayload, eg

将 AJAXcontentType参数设置为application/json并将您的 JSON 对象的字符串化版本作为data有效负载发送,例如

$.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://inputstream, eg

然后您的 PHP 脚本将从php://input流中读取数据负载,例如

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

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

然后您可以将其解析为 PHP 对象或数组...

$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);

回答by PeterKA

Use:

利用:

makeFlickrCall( { data: JSON.stringify( flickr )} );

Instead of

代替

makeFlickrCall(flickr);

Your server-side script should receive your JSON as follows:

您的服务器端脚本应按如下方式接收您的 JSON:

data="{"action":"Flickr","get":"getPublicPhotos"}"