简体   繁体   English

从PHP获取Ajax POST请求中的数据?

[英]Getting data from Ajax POST request in PHP?

I'm trying to send a POST request with Ajax, but I'm having trouble getting the values sent in PHP. 我正在尝试使用Ajax发送POST请求,但是我无法获取PHP中发送的值。 Here's my JavaScript code: 这是我的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. 我想用PHP访问数据。 Something like this? 像这样的东西?

$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']是空的......

Why not use $.post() ? 为什么不使用$.post() The format is: 格式为:

$.post(<URI string>, <postdata object>, <handler>, <datatype>);

And then treat the data like any other form post to PHP (ie use the $_POST variable). 然后将数据像任何其他表单一样处理到PHP(即使用$_POST变量)。

$data = $_POST['data']; - that's wrong. - 那是错的。

$_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); 你可能甚至没有做过那样的操作:JSON.stringify(jsonData); May be will work something like this: $.ajax({..., data: 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? 您应该尝试启动一些流量分析器,例如在谷歌浏览器中按F12(标签网络),或在歌剧中选择歌剧蜻蜓或其他流量分析器并解决一些问题:1。请求发送到正确的脚本而响应不是404错误2.收到的数据格式是否正确? (in google chrome on Network tab, click on request for more info) (在网络标签上的谷歌浏览器中,点击请求获取更多信息)

i think problem will be resolved by this two steps =) 我认为问题将通过这两个步骤解决=)

Number one: you do not need to use JSON.stringify 第一:您不需要使用JSON.stringify

Number two: Access them like so: 第二:像这样访问它们:

$uid = $_POST['UID']; //...etc

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

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