【问题标题】:dynamic json with array带数组的动态 json
【发布时间】:2013-01-31 19:25:31
【问题描述】:

我正在使用 YII,它以“table[attr1]=1&table[attr2]=2&table[attr3]=3”的形式发送数据,以便使用我使用的 jquery 发出请求:

 $.ajax({  
        url:"url",
        data:{
             'table[attr1]':1,
             'table[attr2]':2,
             'table[attr3]':3,
        },
        success:function(resp){
            //ok
        }
    });

但是我需要动态地使这个数据 json,我尝试了这个但是没有用:

$("input").each(function(){ //build the data json       
    form.table[this.name]=this.value;  //the name is 'attr1' , the value is 1
});  



     $.ajax({  
        url:"url",
        data:form, //send the JSON here
        success:function(resp){
            //ok
        }
    });

这将发送空数据

任何想法如何构建这个 json?

【问题讨论】:

    标签: jquery json yii


    【解决方案1】:

    你可以这样做

    var form = {}; // create object
    $('input').each(function(){
        form[this.name] = this.value; // add name/value
    });
    

    然后表单将根据名称/值保存一个对象,并假设您的元素名称是 table[attr1]

    {
      'table[attr1]': 1,
      'table[attr2]': 2,
      'table[attr3]': 3,
    }
    

    【讨论】:

    • 谢谢wirey,我没有使用这种方法,因为我认为会将json变成一个无用的数组
    【解决方案2】:

    这里不涉及 JSON,您发送的是 x-www-form-urlencoded,要使您的代码正常工作,您必须先创建表单对象的 table 属性。

    var form = {table:{}};
    $("input").each(function(){  
        form.table[this.name] = this.value;  //the name is 'attr1' , the value is 1
    });
    $.ajax({  
        url:"url",
        data:form, 
        success:function(resp){
            //ok
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 2015-08-15
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多