【问题标题】:Split POST array into multiple variables将 POST 数组拆分为多个变量
【发布时间】:2012-04-17 11:35:15
【问题描述】:

我现在正在使用 jQuery .post 编写一个表单,负责处理的文件有代码:

print_r($_POST);

返回以下动态输出:

Array ( [data] => capacity=50-1000+people&bookingdate=17%2F04%2F2012&grade=1+star )

我正在尝试将此数组拆分为三个变量,即 容量预订日期等级,但我真的不知道如何.知道怎么做吗?我试过使用 echo $_POST["capacity"]; 但它不起作用。

提前致谢!

编辑

这是我正在使用的 jQuery:

<script type="text/javascript">
$(document).ready(function() {
    $("#postData").click(function() {
        $("#last-step").hide(600);


       $.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
            $("#result").html(data);
      });


        return false;
    });
});
</script>

使用以下表格:

http://jsfiddle.net/xSkgH/93/

【问题讨论】:

  • 看起来您正在对数据进行双重 URL 编码。虽然从字面上回答您的问题很容易,但真正的问题似乎在于您如何从 jQuery 端发布数据。
  • 我想在js中将数据编码成json然后在服务器端解码会更好
  • 展示 jQuery 端是个好主意。
  • 我已经更新了问题以显示 jQuery。

标签: php jquery


【解决方案1】:

我认为你应该改变这一行:

$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {

$.post('resources/process2.php', $("#task5_booking").serialize(), function(data) {

请注意,我将第二个参数从对象文字更改为(url 编码的)字符串。这会将表单中的每个变量作为单独的变量发布(就像直接发布一样)。在服务器端,每个变量都应该在 $_POST 数组中单独可用。

【讨论】:

    【解决方案2】:

    试试parse_str()

    类似:

    parse_str($_POST['data'] , $output);
    
    $capacity = $output['capacity'];
    $bookingdate = $output['bookingdate'];
    $grade = $output['grade'];
    

    【讨论】:

      【解决方案3】:

      你必须为此使用爆炸。

      $data = array();  // A array to store the extracted value
      $temp = explode("&", $data); // First of all explode by "&" to get the each piece
      foreach($temp as $tval) {
         $t = explode('=', $tval); // Next explode by "=" to get the index and value
         $data[$t[0]] = $t[1];  //Add them to the array
      }
      

      另一种选择是使用parse_str()

      $data = array();
      parse_str($_POST['data'], $data);
      

      在这之后所有的值都会被映射到$data

      【讨论】:

        猜你喜欢
        • 2015-09-22
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-25
        • 2013-12-10
        • 1970-01-01
        相关资源
        最近更新 更多