簡體   English   中英

從jquery ajax請求接收$ _POST變量

[英]receive $_POST variables from jquery ajax request

我正在發出一個看起來像的ajax請求

 var object = JSON.stringify(object);
// var url = "http://"+baseURL +"/"+endpoint;

$.ajax({
    contentType: "application/json",
    dataType: 'json',
    type:type,
    data:object,
    url:endpoint,
    success:function(data){
        if (typeof callback == "function"){
            alert(data);
        }
    },

    error: function (xhr, textStatus, errorThrown) {
        console.log(xhr.statusText);
        console.log(xhr.responseText);
        console.log(xhr.status);
        console.log(errorThrown);
    }
});

其中var=object在進入ajax請求之前是一個字符串化的json var=object 在php方面,我正在嘗試通過執行以下操作來捕獲變量

<?php
   echo ($_POST['object']);
   exit;
?>

我的成功回調函數將數據警報為“空”。 我究竟做錯了什么?

謝謝,亞歷克斯

跳過json.stringify,您不希望數據在帖子正文中作為json文本顯示。 要填充帖子數組,需要將其作為application/x-www-form-urlencoded 為此,只需將data屬性設置為對象而不是字符串即可。

// remove this.... var object = JSON.stringify(object);
// var url = "http://"+baseURL +"/"+endpoint;

$.ajax({
    dataType: 'json',
    type:"POST",  // <--- Should be post
    data:object,
    url:endpoint,
    success:function(data){
        if (typeof callback == "function"){
            alert(data);
        }
    },

    error: function (xhr, textStatus, errorThrown) {
        console.log(xhr.statusText);
        console.log(xhr.responseText);
        console.log(xhr.status);
        console.log(errorThrown);
    }
});

可以在當前發送數據時獲取數據,但是您必須在PHP方面進行更多的工作。

$_POST = json_decode(file_get_contents("php://input"),true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM