Is there an inverse function to jQuery serialize?

こ雲淡風輕ζ 提交于 2019-12-07 06:15:36

问题


I can write something, I'm asking if something is already built into jQuery.


回答1:


No there is not.

How would you know which DOM element to change? There could be the same elements with the same name in different forms etc'.

Maybe parseJSON will help you:

jQuery.parseJSON(json) Returns: Object
Description: Takes a well-formed JSON string and returns the resulting JavaScript object.




回答2:


Short Answer: No, there isn't something built into jQuery to do this. Not sure why not...

But here is a jQuery plugin that should do the trick if you are using .serialize() to get a serialized string:

$.fn.deserialize = function (serializedString) 
{
    var $form = $(this);
    $form[0].reset();    // (A) optional
    serializedString = serializedString.replace(/\+/g, '%20'); // (B)
    var formFieldArray = serializedString.split("&");

    // Loop over all name-value pairs
    $.each(formFieldArray, function(i, pair){
        var nameValue = pair.split("=");
        var name = decodeURIComponent(nameValue[0]); // (C)
        var value = decodeURIComponent(nameValue[1]);
        // Find one or more fields
        var $field = $form.find('[name=' + name + ']');

        // Checkboxes and Radio types need to be handled differently
        if ($field[0].type == "radio" || $field[0].type == "checkbox") 
        {
            var $fieldWithValue = $field.filter('[value="' + value + '"]');
            var isFound = ($fieldWithValue.length > 0);
            // Special case if the value is not defined; value will be "on"
            if (!isFound && value == "on") {
                $field.first().prop("checked", true);
            } else {
                $fieldWithValue.prop("checked", isFound);
            } 
        } else { // input, textarea
            $field.val(value);
        }
    });
    return this;
}

(A) The reset at the top is optional. You may want to reset the field values first, or may want to clear them using something like this: https://stackoverflow.com/a/6786237/1766230

(B) See https://stackoverflow.com/a/24417399/1766230 for why we need to replace +.

(C) See Mozilla Developer Javascript Reference for info on decodeURIComponent.

(Note: If you're using .serializeArray() or some other way to serialize your data, the above won't work; you may find some of these solutions useful: jQuery plugin to serialize a form and also restore/populate the form?)

Boring usage example:

var $form = $('form.myFormClass');
var s = $form.serialize();
$form.deserialize(s);

Here's a jsfiddle that let's you play around with setting values, clearing, resetting, and "deserializing": http://jsfiddle.net/luken/4VVs3/



来源:https://stackoverflow.com/questions/9856587/is-there-an-inverse-function-to-jquery-serialize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!