【问题标题】:How to capture json data on php that is sent with ajax (no jquery)如何在 php 上捕获使用 ajax 发送的 json 数据(无 jquery)
【发布时间】:2019-06-27 12:07:51
【问题描述】:

我正在使用 ajax 和纯 javascript 向服务器发送 json 数据。如何获取将在 php 页面上显示 json 内容的$_POST 索引?

ajax 以key=value 的形式向服务器发送请求,同时,通过使用内容类型'application/json',我在下面的链接中得到了一个示例,因为json 数据(stringfy)是直接发送的,没有@ 987654324@.

Sending a JSON to server and retrieving a JSON in return, without JQuery

在post请求的php端,给出了下面的例子。

$v = json_decode(stripslashes(file_get_contents("php://input")))

现在我不明白 php://input 在这里表示什么,因为 json 数据已发送到同一页面。我试过file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); 但它什么也没返回。 我尝试使用var_dump($_POST) 将所有内容作为数组查看,但我得到的只是array(0){}。 那么我如何实际捕获我发送到 php 页面的 ajax (json) 请求? 下面是代码示例:

var data = {
    name : "john",
    Friend : "Jonny",
    Bestie : "johnson",
    neighbour: "john doe"
};
json = JSON.stringify(data);
    var ajax = new XMLHttpRequest(), url = '../handler.php';
    ajax.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        };
    };
    ajax.open('POST', url, true);
    ajax.setRequestHeader('content-type', 'application/json');
    ajax.send(json);

PHP

header("Content-Type: application/json");
var_dump($_POST); 
file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); 

我希望 json 字符串出现在 $_POST 变量中,并且在解码 json 字符串后可以通过它的索引访问,但是我得到 array(0){}null 或根本没有显示任何内容

【问题讨论】:

  • 尝试不使用 stringify,并在网络选项卡下检查您的请求,内容中发送的内容
  • 根据您发送数据的方式,我认为数据是正文的一部分,而不是POST,因此请尝试获取请求的正文。
  • @AhmedSunny,我试过了,没有stringfy,发送到服务器的数据是[object object],结果还是一样。
  • @GetOffMyLawn,我不清楚您所说的 数据是正文的一部分而不是 POST 的意思。如何获取请求的正文?
  • 你应该可以这样得到它:$inputJSON = file_get_contents('php://input'); $input = json_decode($inputJSON);

标签: javascript php json ajax


【解决方案1】:

要获取数组,请将true 参数添加到json_decode()。 在您的代码中:

$body = json_decode(file_get_contents("php://input"), true);
var_export($body);

要在 $_POST 中添加 JSON 数据,您可以使用此代码。

在 JS 中:

json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
  if(this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  };
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
ajax.send('jsn='+json);

在 PHP 中:

$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :[];
var_export($arr);

来源:https://coursesweb.net/ajax/json-from-javascript-php

【讨论】:

  • 我想我刚刚找到了一个新协议php://input,我会花时间了解更多信息。有效。非常感谢coursesWeb。
  • @UchennaAjah Here is a list
猜你喜欢
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
相关资源
最近更新 更多