我如何将其更改为JSON?

时间:2012-05-11 12:48:30

标签: php jquery arrays json foreach

如何使用JSON发送多个值来获取?

foreach($_POST['listItem'] as $key => $values){

    list($eventDate, $eventTitle) = $values;

}

此时,值发送如下。但这似乎不能正常工作,因为它只发送一些字符串。我也无法弄清楚在何处/如何发送caltitle值。

这让我发疯了。任何帮助都会很棒。

var txt = $("#listbox");

            var caltitle = copiedEventObject.title

            var dtstart = $.fullCalendar.formatDate(copiedEventObject.start, 'yyyyMMdd');

            var txt = $('#listbox');     
            txt.append("<li class ='listItem'> " + dtstart + "</li>")

            // remove the element from the "Draggable Events" list
            $(this).remove();           

        }
    });


        $('#calendarform').submit(function(e) {
            var form = $(this);
            var listItems = $('.listItem'); 
            listItems.each(function(index){   //For each event do this:
                var listItem = $(this);
                    $("<input type='hidden'/>").val(listItem.text()).appendTo(form).attr('name', 'listItem[' + index + ']');
                });

            //Get text information from elements

        });

编辑:

(使用JSON)

  $('#calendarform').submit(function(e) {
            var form = $(this);

            var going_to_be_json = [];
            list.each(function(i, item) {
              going_to_be_json.push({
                 'id':'test',
                 'title': 'test'
              });
            });

            $('#stuff').val( JSON.stringify(going_to_be_json) );

     });

2 个答案:

答案 0 :(得分:1)

将数据准备到一个对象数组中,然后使用JSON.stringify()将该数组转换为JSON,并将隐藏的表单值设置为所述字符串(或使用XHR将其提交给服务器)。

以下是如何准备数据的一个非常有限的示例:

var going_to_be_json = [];
list.each(function(i, item) {
  going_to_be_json.push({
     'id':item.id,
     'title': item.title,
     'date': (new Date()).now()
  });
});
hidden_form_element.val( JSON.stringify(going_to_be_json) );

并在服务器上

<?php
$json_data_string = $_POST['hidden_form_field_containing_json_data']; // sanitize however
$array_data = json_decode($json_data_string);

有关json.orgthe Tag Wiki的JSON(Javascript对象表示法)的更多内容已经准备就绪(尽管标记维基只会向您显示更多示例和链接)

似乎你需要一点方向。我希望你不要只复制和粘贴我所拥有的东西,你会阅读并尝试理解它在做什么......

   $('#calendarform').submit(function(e) {
        var form = $(this),
            listItems = $('.listItem'),
            data = [],
            hidden = $('<input />'); // create a hidden field for the form.
                                    // or just select the hidden form element from the page
        hidden[0].type = 'hidden'; // set the type
        hidden[0].name = 'some_name_for_php_to_recognize'; // and name

        listItems.each(function(i,el){ 
             data.push({'index': i, 'text': $(el).text()});
        });

        hidden.val(JSON.stringify(data));
        $(this).append(hidden); // not needed if the hidden element is already in the DOM

    });

答案 1 :(得分:0)

使用jQuery Post或Get方法发送它并通过php获取它可以发送多个值 使用$.post$.get