0

次のような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は、文字列化された json オブジェクトであり、ajax リクエストに組み込まれます。PHP側では、次のようにして変数をキャッチしようとしています

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

私の成功コールバック関数は、データを「null」として警告します。私は何を間違っていますか?

ありがとう、アレックス

4

1 に答える 1

1

投稿本文でデータを json テキストにしたくない json.stringify をスキップします。投稿配列に入力するには、として送信する必要がありますapplication/x-www-form-urlencoded。jquery でこれを行うには、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);
于 2013-07-29T18:57:31.643 に答える