简体   繁体   English

如何在PHP中接收JSON对象?

[英]How to receive JSON object in PHP?

I'm trying to send a JSON object from an AJAX request to my server. 我正在尝试将AJAX请求中的JSON对象发送到我的服务器。

I'm doing this with JQuery like this: 我是这样用JQuery做的:

  $.ajax({
    type: "POST",
    url: settings.ajax.post,
    dataType: 'json',
    data: basket.aggregate(Basket.EXPORT_JSON, qty),
    success: function(data, textStatus, jqXHR) {
      if (typeof settings.ajax.success == "function") settings.ajax.success(data, textStatus, jqXHR);
    },
    error: function(jqXHR, text, e) {
      if (typeof settings.ajax.error == "function") settings.ajax.error(jqXHR, text, e);
    }
  });

The url is pointed to this file on the server: 该URL指向服务器上的此文件:

<?php

$to = "<my-email-address>";
$subject = "JSON test";
$message = "POST dump:\n\n";

foreach($_POST as $key=>$value)
    {
        $message .= $key . ":" . $value;
    }

mail ($to, $subject, $message);

exit;
?>

But the POST var seems to be empty, even though in Firebug I can see that the correct data was sent to the server: 但是POST var似乎是空的,即使在Firebug中我可以看到正确的数据被发送到服务器:

Firebug可以看到JSON对象

After each request is sent, the ajax error function is called, with an undefined error (I guess because there was no reply from the server? Or I don't know?) 发送每个请求后,调用ajax错误函数,出现未定义的错误(我猜是因为服务器没有回复?或者我不知道?)

POST needs key value pairs, but you're just sending it one value (a JSON string) without a key. POST需要键值对,但你只需要发送一个没有键的值(一个JSON字符串)。 It needs to be an array. 它需要是一个数组。

Secondly, you need to decode the JSON before you can use it in PHP as an array or object. 其次,在将PHP用作数组或对象之前,需要解码JSON。 json_decode() is used for that. json_decode()用于此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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