[英]how do I access the object the object i sent to the server file
//向服务器上的php文件发送ajax http post请求,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));
//如果我做 alert(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
?>
我不认为在您的AJAX
请求中需要JSON.stringify(person)
,因为Object
所有keys
都已经在strings
。
由于您使用的是POST
方法,因此您可以直接访问该对象,例如
print_r ($_POST['person']);
您可以使用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 中以$_POST['firstName']
等形式访问它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.