简体   繁体   English

PHP $ _POST在AJAX发布请求期间为空

[英]PHP $_POST empty during AJAX post request

Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer) 目标:序列化数据,使用AJAX在HTTP POST请求中发送数据,在PHP中处理数据(并回答)

Problem: PHP $_POST variable seems to be empty 问题: PHP $ _POST变量似乎为空

JS/AJAX JS / AJAX

var postData = [cmd, data];
alert(postData = JSON.stringify(postData));

$.ajax({
   url: "./backendTag.php",
   type: "post",
   data: postData,
   dataType: 'json',
   success: function (response) {
      alert(response); // Empty
      //logToServerConsole(JSON.parse(response));
   },
   error: function(jqXHR, textStatus, errorThrown) {
      logToServerConsole("E3"); // Communication Error
      console.log(textStatus, errorThrown);
   }
});

PHP PHP

<?php echo json_encode($_POST);

The reason for the same is probably because you are not posting properly in javascript. 这样做的原因可能是因为您没有在javascript中正确发布。 Before i add the codes, let me add a couple of tips on how to debug in these situations. 在添加代码之前,让我添加一些有关如何在这些情况下进行调试的提示。

First is, you check if the request is properly formed. 首先,您检查请求的格式是否正确。 Inspect the network in browser dev tools. 在浏览器开发工具中检查网络。

Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP 第二种方法是在$ _POST上使用var_dump列出所有post参数,并检查它们是否已在PHP中接收到。

Now as far as the code goes 现在就代码而言

here is the javascript 这是JavaScript

$.ajax({
  method: "POST",
  url: "url.php",
  data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
  alert(msg);
});

and in php you can simply check using 在PHP中,您可以简单地使用

<?php
print $_POST["name"];
?>

which would work perfectly. 这将完美地工作。 Notice how the data in javascript is a list, while from what you wrote seems to be json string 请注意,javascript中的数据是如何列表的,而从您写的内容来看似乎是json字符串

Apparently we can't pass an array directly after serializing him. 显然我们不能在序列化他之后直接传递数组。 The following code resolved the problem. 以下代码解决了该问题。 (Split array) (拆分数组)

data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};

$.ajax({
   url: "./backendTag.php",
   type: "post",
   data: JSONata,
   dataType: 'json',

   /* Handlers hidden*/
});

JSON content won't be parsed to the $_POST globals. JSON内容不会解析为$ _POST全局变量。 If you want to reach them, try to get from php://input with: 如果您想达到这些目标,请尝试从php:// input获取:

file_get_contents('php://input')

And I suggest giving the content-type during the ajax request: 而且我建议在ajax请求期间提供content-type:

contentType: 'application/json',

If it's not working, try to set the data as a string, with JSON.Stringify, like the following: 如果不起作用,请尝试使用JSON.Stringify将数据设置为字符串,如下所示:

data: JSON.stringify(postData)

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

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