zoukankan      html  css  js  c++  java
  • 构造AJAX参数, 表单元素JSON相互转换

    ajax提交服务器数据, 整理一下转换方法。

    HTML:

       <form id="fm" name="fm" action="">
            <input name="UserName" type="text" value="UserName1"/>
        </form>
        <input name="UserId" id="UserId" type="text" value="UserId1"/>

    1.表单元素转QueryString

    var q = $('#fm,#UserId').serialize(); //q = UserName=UserName1&UserId=UserId1

    2.字符串, JSON 互相转换

    var obj = jQuery.parseJSON('{"name":"John"}');
    alert( obj.name === "John" );

    可以利用jquery-json插件实现转换,直接引用示例

    var thing = {plugin: 'jquery-json', version: 2.3};
    var encoded = $.toJSON( thing );
    // '{"plugin":"jquery-json","version":2.3}'
    var name = $.evalJSON( encoded ).plugin;
    // "jquery-json"
    var version = $.evalJSON(encoded).version;
    // 2.3

    3.表单,元素转Name,Value数组

    var arr = $("#fm,#UserId").serializeArray();
    /*[ 
         {name: 'UserName', value: '"UserName"1'}, 
         {name: 'UserId', value: 'UserId'}
      ] */

    4. 表单元素转JSON

    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
    var obj = $('form').serializeObject();
    /*obj: Object
    UserId: "UserId1"
    UserName: "UserName1"
    __proto__: Object*/

    5. JSON2FORM

    $.getJSON('url_to_file', function(data) {
        for (var i in data) {
            $('input[name="'+i+'"]').val(data[i]);
        }
    }

    Google过程中发现一个更强大的插件 http://code.google.com/p/jquery-load-json/

    data = {
                        "Name":"Emkay Entertainments",
                        "Address":"Nobel House, Regent Centre",
                        "Contact":"Phone"
            }  
     $('div#data').loadJSON(data);
     
     <div id="data">
                <h1 id="Name">Emkay Entertainments</h1>
                <label for="Address">Address:</label>
                <span id="Address">Nobel House, Regent Centre</span>        
                <label for="Contact">Contact by:</label>
                <span id="Contact">Phone</span>
            </div>

    live demo :http://jquery-load-json.googlecode.com/svn/trunk/edit.html?ID=

    ajax提交参数是,要注意提交参数的类型。如easyui grid 参数只能用JSON,不支持QueryString

  • 相关阅读:
    C++中类模板的概念和意义
    C++中模板类声明和实现能否分离?
    C/C++ 关于大小端模式,大小端字节序转换程序
    C++中的赋值操作符重载和拷贝构造函数
    C++中的友元
    C/C++内存对齐详解
    C++ 虚函数表、函数地址、内存布局解析
    虚析构函数的必要性(C++)
    C++中的抽象类和接口
    C++中的单例类模板
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/4528067.html
Copyright © 2011-2022 走看看