douqian5553 2017-08-13 07:04
浏览 298
已采纳

通过POST将JSON数据发送到PHP

I'm trying to send the JSON below to a PHP script via the POST method.

{
  "operation": {
    "name": "Nicolas",
    "age": 24,
    "sex": "Male",
  }
}

What I wanna do is handle the information that is coming from the JSON like name, age, sex, and print unto the PHP response.

How can I do this?

  • 写回答

3条回答 默认 最新

  • dragon7713 2017-08-13 07:16
    关注

    This is how I did with AJAX request to send json data to my URL:

    var dataToSend = {
                    name: "Nicolas",
                    age: 24,
                    sex: "Male"
                }
    
                var jsonDataToSend = JSON.stringify(dataToSend);
    
                $.ajax({
                   type:'POST',
                   url: "/your-url",
                   data: jsonDataToSend,
                   success:function(data){
    
                        console.log("success");
                   },
                   error: function (data) {
    
                        console.log("error");
                    }
                });
    

    And how to receive this posted data in request handler on PHP side:

    $postbody = $request->json()->all();
    
    $name = $postbody['name'];
    $age = $postbody['age'];
    $sex = $postbody['sex'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?