【问题标题】:Send Json Array Through jQuery Ajax通过 jQuery Ajax 发送 Json 数组
【发布时间】:2013-01-09 12:02:32
【问题描述】:

我将通过 jquery ajax 调用将一个 json 对象数组发送到一个 php 文件。

var arr = new Array();
var record1 = {'a':'1','b':'2','c':'3'};
var record2 = {'d':'4','e':'5','f':'6'};
arr.push(record1);
arr.push(record2);

如何通过 jquery ajax 发送数组?以及如何获取 php 中的值? 谢谢。

【问题讨论】:

  • 你需要序列化 ​​json 对象并在你的 PHP 代码中反序列化它......!!

标签: php json jquery getjson


【解决方案1】:
$.ajax({
        url: "api",
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(arr),
        success: function(response){}

       });

使用 PHP:

$strRequest = file_get_contents('php://input');
$Request = json_decode($strRequest);

【讨论】:

    【解决方案2】:

    我认为JSON.stringify() 可能有用。

    或者,您可以在 php 文件中使用json_decode()

    【讨论】:

      【解决方案3】:

      首先下载并添加插件:jquery.json-2.4.js 到您的项目中。 这个插件提供了很多帮助,让你的生活更轻松。

      然后在你的 $.ajax 中,使用 data : $.toJSON(arr),

      【讨论】:

        【解决方案4】:

        您首先要知道的是,您需要拥有两个文件才能使事情变得简单。 1.你要把你的php代码phpcode.php放在哪里 2. 你要把你的 ajax 代码 ajax.html 放在哪里 在您要放置 ajax 代码的页面中,确保您连接到 jquery 插件 那么

         <script> 
                  $(document).ready(function(){
              // your ajax code here  delete mine and put your codes
            $.getJSON(' phpcode.php ', function(data) {
                      $('#myJson').html('<table style="color:red"><tr><td>' + data.name + '</td><td>' + data.user + '</td></tr></table>');
                    });
                  });
        
                </script>
            <body>
            <!—You may put the bellow div in the ajax page so that u load your data in it ---->
                <div id="myJson"></div>
              </body>
            </html>
             In your php page you need something like this at the end of your code 
            // The JSON standard MIME header.
            header('Content-type: application/json');
            echo  json_encode($array);
            Note: I took an example from my working codes just to save the time but I think you get the Idea
        

        【讨论】:

          猜你喜欢
          • 2015-07-20
          • 2012-01-24
          • 1970-01-01
          • 2013-03-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-17
          • 1970-01-01
          相关资源
          最近更新 更多