Javascript 如何访问发送到服务器文件的对象

Javascript 如何访问发送到服务器文件的对象,javascript,php,ajax,Javascript,Php,Ajax,//将ajax http post请求发送到服务器上的php文件,post//请求是一个简单的对象 var xhr = new XMLHttpRequest(); var person = { "firstName" : "Adebowale", "lastName" : "Johnson", "ago" : 43 } xhr.open("POST","phfile.php",true); xhr.setRequestHeader("Content-type","app

//将ajax http post请求发送到服务器上的php文件,post//请求是一个简单的对象

var xhr = new XMLHttpRequest();
var person = {
    "firstName" : "Adebowale",
    "lastName" : "Johnson",
    "ago" : 43
}

xhr.open("POST","phfile.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-     urlencoded");

xhr.onreadystatechange = function() {
    if(xhr.readyState === 4) {
        var status = xhr.status;
        if((status >= 200) && (status < 300) || (status === 304)) {

            alert(xhr.responseText);

        }
    }
};

xhr.send(JSON.stringify(person));
var xhr=new-XMLHttpRequest();
个人变量={
“名字”:“Adebowale”,
“姓氏”:“约翰逊”,
“以前”:43
}
open(“POST”,“phfile.php”,true);
setRequestHeader(“内容类型”、“应用程序/x-www-form-urlencoded”);
xhr.onreadystatechange=函数(){
if(xhr.readyState==4){
var status=xhr.status;
如果((状态>=200)和&(状态<300)| |(状态==304)){
警报(xhr.responseText);
}
}
};
send(JSON.stringify(person));
//如果我发出警报(xhr.responseText); //我从浏览器中获取对象{}

//在服务器上,使用php,我如何访问对象,如果我执行echo或//print\r,我将得到空对象--object{},其中没有任何属性

//从我提问的语气可以看出,我对所有这些还是很陌生,我只是想学习

//在我的phfile.php上,我设置了以下php代码

<?php

print_r 
//How do I access the object I sent to this file please
?>

您可以使用
STDIN
读取原始POST数据:

$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;
通过将数据作为URL编码的表单字段传递,您可以简化所有这一切:

xhr.send('firstName=' + encodeURIComponent(person.firstName) + '&lastName=' + encodeURIComponent(person.lastName) + '&ago=' + encodeURIComponent(person.ago);

然后你可以在PHP中以
$\u POST['firstName']
等方式访问它们。

我认为在你的
AJAX
请求中不需要
JSON.stringify(person)
,因为
对象的所有
键都已经在
字符串中了

由于您使用的是
POST
方法,因此可以像

print_r ($_POST['person']);

我们需要查看您的“ajax http post请求”和“服务器上的php文件”。单击问题下方的“编辑”并添加代码。如果发送了原始json字符串,可能需要从
php://input
。您好,我已经添加了最初的ajax http post请求,请大家抽时间看看。我还是被卡住了。无法访问我在服务器上发送的对象。为什么要尝试将参数作为JSON而不是普通URL编码的数据传递?然后您可以使用
$\u POST
读取值。您好,谢谢您的回复,但我没有在文件中发送对象,它直接附加到ajax http POST请求中。我已经编辑了原始问题,添加了我的全部代码。请看一看,;我的答案中没有文件。是的,我知道,我只是想fgets()方法读取一个文件。在任何情况下都会收到错误消息-使用未定义的常量STDIN。谢谢。抱歉,忘记了STDIN仅在从CLI而不是Web服务器运行时可用。我已修改为使用
php://input
Cheers Barmar,但不幸的是,仍然得到了通知:尝试获取非对象的属性…您好,感谢您的响应,但当我打印时,仍然在php文件上出现“undefined index:person…”错误($\u POST['person');删除此行==>xhr.setRequestHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);