簡體   English   中英

使用 POST 發送 JSON 對象

[英]Send JSON object with POST

我想用 POST 發送一個 JSON 對象

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

這就是我發送對象的方式:

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

問題:如何在服務器端 php 中讀取對象? 發送的 json 的關鍵是什么?

echo var_dump ( $_POST ) ; 顯示

  array (size=0)
  empty

問題是什么?

編輯后

我將代碼更改為:

this.objJSON = jsonObj;

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

我嘗試閱讀 JSON obj :

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

......仍然是同樣的事情:

is not set

array (size=0)
  empty

我不確定 PHP 是否可以自動將 JSON 解析為$_POST變量。 您應該將 JSON 放入普通 POST 變量的值中:

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

並使用默認的 Content-Type。 然后在 PHP 中你可以這樣做:

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

您還需要修復 Javascript 變量,如 Niels Keurentjes 的回答中所述。

將您的功能分解為核心 3 行:

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

jsonOBJ在本地范圍內設置為變量。

this.objJSON = jsonObj;

jsonOBJ被復制到this.objJSON

sendPostRequest(objJSON);

仍然沒有局部變量objJSON因為 Javascript 不會自動考慮局部范圍的this部分,因此發送 null,因此空$_POST

改為發送jsonOBJthis.objJSON ,它會正常工作。

嘗試 :

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

它是一個鍵值對,我猜你缺少鍵。

對於您的原始 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