【问题标题】:PHP receive jsonPHP接收json
【发布时间】:2012-03-06 01:29:15
【问题描述】:

我正在使用淘汰赛,这是我的 ajax 代码:

save: function() {
                $.ajax({
                    url:"http://localhost/loyalty/welcome/json/",
                    type: "post",
                    data: ko.toJSON(this),
                    contentType: "application/json",
                    success: function (result) { alert(result) }
                });
            }

使用firebug我可以看到json消息发送正确,问题是如何在PHP上接收它,发送的名称是什么?

我正在使用 CodeIgniter

提前感谢您的帮助。

【问题讨论】:

    标签: php ajax json knockout.js


    【解决方案1】:

    它将位于变量 $_POST['key'] 中,其中 'key' 是 JSON 对象中的键值。

    【讨论】:

    • 嗨...我收到了这个 JSON: [{"name":"João","isOnTwitter":false}] 并且使用 $_POST['name'] 什么都不返回。
    • 您的 JSON 在一个数组中。你会希望它在一个裸露的对象中,周围只有{}。否则它是一个数组,你需要给它一个名字。类似{"jsonval":ko.toJSON(this)}
    • 表单数据不使用 json 传递。 HTTP 有自己的数据传输格式。使用 form.serialize()
    • 如何只返回 JSON 而不是数组?
    • @SomeshMukherjee jQuery ajax 函数中的data 值可以通过列出的对象格式传递。序列化是另一种方式,也是有效的
    【解决方案2】:
        **This is what exactly the way to post as json way**
    
    //index.php
         $(document).ready(function(){
                   obj = {}
                   obj.name = "sam"
                   obj.value = "12345"
                          $.ajax({
                                   url:"json.php",
                                   type: "post",
                                   data :obj,
                                   dataType:"json",
                                   success: function (result) {
                                        alert(result.name);
                                   }
                                 });
                }); 
    
        //json.php  ,, the posted data is received as array ,, so we need to convert it as //json_encode to make as JSON again 
    
        <?php
        $jsonReceiveData = json_encode($_POST);
        echo $jsonReceiveData;
        ?>
    

    【讨论】:

      【解决方案3】:
        save: function() {
                  $.ajax({
                      url:"http://localhost/loyalty/welcome/json/",
                      type: "post",
                      data: $(this).serialize()/*Where this is an instance of the form change with appropriate selector such as #loginForm*/,
                      contentType: "application/json",
                      success: function (result) { alert(result) }
                  });
              }
      

      在php文件中使用$_POST获取数据 我假设您也在使用 jquery,而 $ 是 jquery 函数。现在,这些数据在 post superglobal 中可用。注意:您不需要使用 json 通过 ajax 函数发送数据。数据以序列化数组格式传递,例如:field1=value1&field2=value2 等...

      如果您必须使用 json,坦率地说这是不必要的,请使用 data:"json="+ko.toJSON(form)

      在服务器端 data=json_decode($_POST['json']);

      【讨论】:

        【解决方案4】:

        解决办法是采取

        contentType: "application/json",
        

        来自 ajax 调用。

        =)

        【讨论】:

          猜你喜欢
          • 2012-03-06
          • 2018-09-17
          • 1970-01-01
          相关资源
          最近更新 更多