从 PHP 中的 Ajax POST 请求获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7986285/
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
Getting data from Ajax POST request in PHP?
提问by bsand
I'm trying to send a POST request with Ajax, but I'm having trouble getting the values sent in PHP. Here's my JavaScript code:
我正在尝试使用 Ajax 发送 POST 请求,但无法获取以 PHP 发送的值。这是我的 JavaScript 代码:
$.ajax({
url: "updatedata.php",
type: 'post',
data: JSON.stringify(jsonData),
contentType: 'application/json',
dataType: 'json',
success: function(data, status, xhr)
{
//...
}
});
And I want to access the data with PHP. Something like this?
我想用 PHP 访问数据。像这样的东西?
$data = $_POST['data'];
My data:
我的数据:
{"UID":"00a3b1b0-03b4-11e1-be50-0800200c9a66","Firstname":"Bastian","Lastname":"Sander","UserPenaltys":{"Penalty1":"110","Penalty10":"200","Penalty11":"210","Penalty12":"220","Penalty13":"230","Penalty14":"240","Penalty15":"250","Penalty16":"260","Penalty2":"120","Penalty3":"130","Penalty4":"140","Penalty5":"150","Penalty6":"160","Penalty7":"170","Penalty8":"180","Penalty9":"190"},"PenaltyCounter":16}
I tried this:
我试过这个:
$.post("updatedata.php", JSON.stringify(UserData), function (data) {
}, "json");
But $_POST['Firstname']
is empty...
但是$_POST['Firstname']
空...
回答by Crontab
Why not use $.post()
? The format is:
为什么不使用$.post()
?格式为:
$.post(<URI string>, <postdata object>, <handler>, <datatype>);
And then treat the data like any other form post to PHP (i.e. use the $_POST
variable).
然后将数据像任何其他表单发布到 PHP 一样处理(即使用$_POST
变量)。
回答by MaxXx1313
$data = $_POST['data'];
- that's wrong.
$data = $_POST['data'];
- 那是错误的。
$_POST['UID']
, $_POST['Firstname']
, $_POST['Lastname']
etc. only be avalable
$_POST['UID']
, $_POST['Firstname']
,$_POST['Lastname']
等等. 仅可用
It can be you even hadn't make some operation like that: JSON.stringify(jsonData); May be will work something like this: $.ajax({..., data: jsonData, ...});
可能你甚至没有做过这样的操作: JSON.stringify(jsonData); 可能会像这样工作:$.ajax({..., data: jsonData, ...});
You should try to start some traffic analyzer, for example press F12 in google chrome (tab Network), or select opera dragonfly in opera, or another trafic analyzer and resolve some question: 1. is request send to right script and response not an 404 error 2. is received data has right format? (in google chrome on Network tab, click on request for more info)
您应该尝试启动一些流量分析器,例如在谷歌浏览器(标签网络)中按 F12,或在歌剧中选择歌剧蜻蜓,或其他流量分析器并解决一些问题:1. 请求发送到正确的脚本和响应不是 404错误 2. 接收到的数据格式是否正确?(在网络标签上的谷歌浏览器中,点击请求获取更多信息)
i think problem will be resolved by this two steps =)
我认为这两个步骤将解决问题 =)
回答by Naftali aka Neal
Number one: you do not need to use JSON.stringify
第一:你不需要使用 JSON.stringify
Number two: Access them like so:
第二:像这样访问它们:
$uid = $_POST['UID']; //...etc
$uid = $_POST['UID']; //...etc