最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to serialize an array? - Stack Overflow

programmeradmin5浏览0评论

I have problems with serializing array of events from jQuery's fullcallendar plugin.

The problem is that each event object contains property 'Source' that has self-references to the event.

  • Either I need to iterate through the array, create a new object, pass those elements and properties that I need to serialize (skipping unnecessary ones) and then apply serialization to that object.
  • or I have to find a way to serialize it "as is".

Would you help me with syntax on first (because I'm not so good in jQuery and javascript), or show me please the right way on second.

I think I need something in javascript that would be equivalent of something c#'s

public class Event{
   public string Name;
   public Event  Source;
}

public class EventNoSource{
   public string Name;
}

var events = new List<Event>();

var ev1 = new Event{Name = "ev1"};
ev1.Source = ev1;
events.Add(ev1);

var ev2 = new Event{Name = "ev2"};
ev2.Source = ev2;
events.Add(ev2);

var eventsPlain = new List<EventNoSource>();
events.ForEach(x=> eventsPlain.Add(new EventNoSource{Name = x.Name}));

I have problems with serializing array of events from jQuery's fullcallendar plugin.

The problem is that each event object contains property 'Source' that has self-references to the event.

  • Either I need to iterate through the array, create a new object, pass those elements and properties that I need to serialize (skipping unnecessary ones) and then apply serialization to that object.
  • or I have to find a way to serialize it "as is".

Would you help me with syntax on first (because I'm not so good in jQuery and javascript), or show me please the right way on second.

I think I need something in javascript that would be equivalent of something c#'s

public class Event{
   public string Name;
   public Event  Source;
}

public class EventNoSource{
   public string Name;
}

var events = new List<Event>();

var ev1 = new Event{Name = "ev1"};
ev1.Source = ev1;
events.Add(ev1);

var ev2 = new Event{Name = "ev2"};
ev2.Source = ev2;
events.Add(ev2);

var eventsPlain = new List<EventNoSource>();
events.ForEach(x=> eventsPlain.Add(new EventNoSource{Name = x.Name}));
Share Improve this question edited Mar 29, 2011 at 17:42 iLemming asked Mar 28, 2011 at 22:21 iLemmingiLemming 36.4k61 gold badges198 silver badges316 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

from the jQuery doc.

var myObject = {
  a: {
    one: 1, 
    two: 2, 
    three: 3
  }, 
  b: [1,2,3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));

alert(recursiveEncoded);
alert(recursiveDecoded);

try to execute it. Is it what You need?

if You have already defined $ variable in Your code somewhere (because of using other tools), You can try to use this call:

jQuery.param(myObject)

I have developed a jQuery plugin that serializes elemental types, arrays and objects into DOM elements. I still do not know how to serialize closures, though.

(function($) {

$.identity = function(key, value) {
    return value;
};

$.fn.tag = function(index) {
    return this
    .get(index || 0)
    .nodeName
    .toLowerCase();
};

$.fn.append2 = function(collection, callback) {
    var $this = this;

    // The default callback does nothing.
    callback = callback || $.identity;

    // Apply the callback to each element of the
    // collection, and append the result.
    $.each(collection, function(key, value) {
        $this.append(callback(key, value));
    });

    return this;
};

$.serialize = function(key, value) {
    if (!value) {
        // No arguments? Return empty selector.
        if (!key && key !== 0)
            return $();

        // Swap arguments.
        value = key;
        key   = null;
    }

    var $this = (typeof value === 'object')

        // Serialize into <div>.
        ? $('<div>')
        .append2(value, $.serialize)
        .addClass(value.constructor === Array
            ? 'array' : '')

        // Serialize into <input>.
        : $('<input>').val(value);

    // Name the element.
    if (key != null)
        $this.attr('name', key);

    return $this;
};

$.fn.deserialize = function() {
    if (this.length !== 1)
        return null;

    var tag = this.tag();

    // Deserialize into elementary value?
    if (tag === 'input')
        return this.val();

    // Unable to deserialize?
    if (tag !== 'div')
        return null;

    // Deserialize into array/object.
    var array = this.hasClass('array');
    var res   = array ? [] : {};

    // Deserialize members into sub-elements.
    this
    .children('div[name],input[name]')
    .each(function() {
        var $this = $(this);
        var name  = $this.attr('name');
        var value = $this.deserialize();
        res[array ? +name : name] = value;
    });

    return res;
};

})(jQuery);

Here is an example:

File 1: test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="text/javascript" src="latest-jquery.js"></script>
  <script type="text/javascript" src="test.js"></script>
  <title>Example</title>
</head>

<body>
  <div style="display: none" id="info">
    <input name="name" value="Eduardo León"/>
    <input name="age" value="23"/>
    <input name="degree" value="Systems Engineer"/>
    <div class="array" name="relatives">
      <div name="0">
        <input name="relationship" value="Significant Other"/>
        <input name="name" value="Kelly Cruz"/>
      </div>
      <div name="1">
        <input name="relationship" value="Son"/>
        <input name="name" value="Mauricio León"/>
      </div>
    </div>
  </div>
</body>

</html>

File 2: test.js

$(document).ready(function() {
    var $sel = $('#info');

    // Retrieve information contained in
    // the original HTML document.
    var info = $sel.deserialize();
    alert(info.name);
    alert(info.age);
    alert(info.degree);
    alert(info.relatives.length);
    $.each(info.relatives, function(index, relative) {
        alert(relative.relationship);
        alert(relative.name);
    });

    // Update information with a list of ics.
    $sel.append($.serialize('ics', [
        {name: 'xkcd',            author: 'Randall Munroe'},
        {name: 'Dinosaur Comics', author: 'Ryan North'}
    ]));

    // Re-retrieve the information, including the list of ics.
    info = $sel.deserialize();
    $.each(info.ics, function(index, ic) {
        alert(ic.name);
        alert(ic.author);
    });
});

This is something I've always wanted to change with fullcalendar. I wanted to remove the source property, and make it accessible through a method instead. If you you'd like to add this to the issue tracker, here ya go: http://code.google./p/fullcalendar/issues/list

 $.each(events, function(index, value) { 
                                         var ev = new Object();
                                         ev.name = value.name;
                                        }
发布评论

评论列表(0)

  1. 暂无评论