简体   繁体   English

使用 POST 发送 JSON 对象

[英]Send JSON object with POST

I want to send a JSON object with POST我想用 POST 发送一个 JSON 对象

var user = {
    "first_name": first_name.value,
    "last_name": last_name.value,
    "age": age.value,
    "email": email.value
};   

This is how I send the object :这就是我发送对象的方式:

var request;
var url = 'ajax_serverside_JSON.php';
var destination;

function ajax_call(src, jsonObj, dst, method) {

    this.src = src;
    destination = dst;
    this.objJSON = jsonObj;
    this.request = getXMLHttpRequest();
    this.request.onreadystatechange = getResponse;
    if (method == 'POST') {
        sendPostRequest(objJSON);
    }
    return;
}

function sendPostRequest(objJSON) {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    request.send(JSON.stringify(objJSON));
    return;
}

function getXMLHttpRequest() {
    try {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera,Safari
            request = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            request = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } catch (e) {
        alert('The browser doesn\'t support AJAX: ' + e);
        request = false;
    }
    return request;
}

function getResponse() {
    if (request.readyState == 4 && request.status == 200) {
        document.getElementById(destination).innerHTML += request.response;
    }
}

Question: how do I read the object in the server side php ?问题:如何在服务器端 php 中读取对象? What is the key o the sent json ?发送的 json 的关键是什么?

echo var_dump ( $_POST ) ; echo var_dump ( $_POST ) ; shows显示

  array (size=0)
  empty

What is the problem?问题是什么?

AFTER EDIT编辑后

I changed my code to :我将代码更改为:

this.objJSON = jsonObj;

and

request.send("user=" + JSON.stringify(this.objJSON));

I try reading the JSON obj :我尝试阅读 JSON obj :

<?php
if (isset ( $_POST ['user'] )) {
    $obj = json_decode ( $_POST ['user'] );
    echo "isset";
} else {
    echo "is not set ";
    echo var_dump ( $_POST );
}
?>

...and still the same thing : ......仍然是同样的事情:

is not set

array (size=0)
  empty

I'm not sure that PHP can automatically parse JSON into $_POST variables.我不确定 PHP 是否可以自动将 JSON 解析为$_POST变量。 You should put the JSON into the value of a normal POST variable:您应该将 JSON 放入普通 POST 变量的值中:

request.send('data=' + encodeURIComponent(JSON.stringify(objJSON));

and use the default Content-Type.并使用默认的 Content-Type。 Then in PHP you can do:然后在 PHP 中你可以这样做:

var_dump(json_decode($_POST['data']));

You also need to fix a Javascript variable, as explained in Niels Keurentjes's answer.您还需要修复 Javascript 变量,如 Niels Keurentjes 的回答中所述。

Breaking your function down to its core 3 lines:将您的功能分解为核心 3 行:

function ajax_call(src, jsonObj, dst, method) {

jsonOBJ is set in local scope as a variable. jsonOBJ在本地范围内设置为变量。

this.objJSON = jsonObj;

jsonOBJ is copied to this.objJSON . jsonOBJ被复制到this.objJSON

sendPostRequest(objJSON);

There is still no local variable objJSON since Javascript does not automatically consider this part of the local scope, hence null is sent, hence the empty $_POST .仍然没有局部变量objJSON因为 Javascript 不会自动考虑局部范围的this部分,因此发送 null,因此空$_POST

Send jsonOBJ or this.objJSON instead and it'll work fine.改为发送jsonOBJthis.objJSON ,它会正常工作。

Try :尝试 :

request.send("obj="+JSON.stringify(objJSON));

its a key value pair, I guess you are missing key.它是一个键值对,我猜你缺少键。

For your original Ajax request, you'll have to read the request body from php://input and decode then it.对于您的原始 Ajax 请求,您必须从php://input读取请求正文,然后对其进行解码。

<?php
$post = json_decode(file_get_contents('php://input'));
if (isset ( $post ['user'] )) {
    echo "isset";
} else {
    echo "is not set ";
    echo var_dump ( $post );
}
<script>
var user = {
                "first_name" : first_name.value,
                "last_name" : last_name.value,
                "age" : age.value,
                "email" : email.value
            };

$.customPOST = function(data,callback){
  $.post('your_php_script.php',data,callback,'json');
}

$(document).ready(function() {
    //suppose you have a button "myButton" to submit your data
    $("#myButton").click(function(){
        $.customPOST(user,function(response){
         //on the server side you will have :
         //$_POST['first_name'], $_POST['last_name'], .....
         //server will return an OBJECT called "response"
         //in "index.php" you will need to use json_encode();
         //in order to return a response to the client
         //json_encode(); must have an array as argument
         //the array must be in the form : 'key' => 'value'
        });
        return false;
    });
</script>

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

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