我怎么访问对象我发送到服务器文件的对象发送到、象我、对象、服务器

2023-09-10 19:44:19 作者:冷眸

//发送一个ajax HTTP POST请求到服务器上的PHP文件,后//请求是一个简单的对象。

  VAR XHR =新XMLHtt prequest();
变种人= {
    名字:Adebowale
    姓氏:强生,
    前:43
}

xhr.open(POST,phfile.php,真正的);
xhr.setRequestHeader(内容型,应用/的X WWW的形式 -  urlen codeD);

xhr.onreadystatechange =功能(){
    如果(xhr.readyState === 4){
        VAR状态= xhr.status;
        如果((状态> = 200)及及(状态&所述; 300)||(状态=== 304)){

            警报(xhr.responseText);

        }
    }
};

xhr.send(JSON.stringify(人));
 

//如果我做的警报(xhr.responseText); //我从浏览器对象{}。

//在服务器上,使用PHP,我该如何访问这个对象,如果我做回应或// print_r的,我得到的空对象---对象{}以无属性。

//正如你可以告诉我问题的语气,还是很新的所有//这些,我只是努力学习吧。

//我phfile.php,我设置了下面的PHP code ...

 < PHP

的print_r
//我如何进入我送到这个文件的对象,请
?>
 

解决方案 服务器不能创建对象

您可以使用读取原始POST数据标准输入

  $ post_data =的fopen(PHP://输入,R);
$ JSON =与fgets($ post_data);
$对象= json_de code($ JSON);
$的firstName = $对象 - >的firstName;
$的lastName = $对象 - >的lastName;
$年龄= $对象 - >年龄;
 

您可以通过刚好路过的数据作为URL-CN codeD表单域简化了这一切:

  xhr.send('的firstName ='+ EN codeURIComponent(person.firstName)+'&放大器; lastName的='+ EN codeURIComponent(person.lastName)+ '和;以前='+ EN codeURIComponent(person.ago);
 

然后,你可以访问它们,就像 $ _ POST ['的firstName'] 等在PHP。

//Sent an ajax http post request to a php file on the server, the post //request is a simple object.

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));

//if I do alert(xhr.responseText); //I get object{} from the browser.

//On the server, using php, how do I access the object, if I do echo or //print_r, I get the empty object --- object{} with none of the properties.

//As you can tell from the tone of my question, am still very new to all //these, am just trying to learn please.

//on my phfile.php, I set up the following php code...

<?php

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

解决方案

You can read raw POST data using STDIN:

$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;

You could simplify all of this by just passing the data as URL-encoded form fields:

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

Then you can just access them as $_POST['firstName'], etc. in PHP.