将数据表单作为对象的Json文件

时间:2016-01-09 11:43:42

标签: php json ajax html5

我的json对象应该如下所示,这是在提交表单时生成的:

{             "范围":{                 " l1_price&#34 ;:                     {"来自":" 0","到":" 260k","价格":" Rs .02"},                 " l2_price&#34 ;:                     {"来自":" 260k","到":" 500k","价格":" Rs .04"},                 " l3_price&#34 ;:                     {"来自":" 500k","到":" 1MM","价格":" Rs .007"},                 " l4_price&#34 ;:                     {"来自":" 1MM","到":" 2MM","价格":" Rs .003"}              }

    }

现在表单如下:

     <form class="json_out">
        <p>
          l1_price:
          <input type="text" name="from_l1" placeholder="from range">
          <input type="text" name="to_l1" placeholder="to range">
          <input type="text" name="price_l1" placeholder="price">
        </p>
        <p>
          l2_price:
          <input type="text" name="from_l2" placeholder="from range">
          <input type="text" name="to_l2" placeholder="to range">
          <input type="text" name="price_l2" placeholder="price">
        </p>
        <p>
          l3_price:
          <input type="text" name="from_l3" placeholder="from range">
          <input type="text" name="to_l3" placeholder="to range">
          <input type="text" name="price_l3" placeholder="price">
        </p>
        <p>
          l4_price:
          <input type="text" name="from_l4" placeholder="from range">
          <input type="text" name="to_l4" placeholder="to range">
          <input type="text" name="price_l4" placeholder="price">
        </p>    
        <p>
          <input type="submit" value="Submit">
          <input type="reset" value="Reset">
        </p>
    </form>

最后我想在提交表单时将数据发送到data.json文件。

JavaScript代码:

<script>
$('form.json_out').submit(function(e) {
    var values = {};
    var range = {};
    var rates = [];
    var thresholds = [];
    var result = {};
    e.preventDefault();
    $.each($('form.json_out').serializeArray(), function(i, field) {
        if(field.name){
            temp = {};
            name_split = field.name.split('_');
            price_lev = name_split[1] + '_' + 'price';
            val_str = name_split[0];
            val = field.value;
            temp[val_str] = val
            if (val_str == 'price'){rates.push(val)};
            if (val_str == 'to'){thresholds.push(val)};
            if (range[price_lev]){
                res = range[price_lev]
                res[val_str] = val
                range[price_lev] = res
            }
            else{
                range[price_lev] = temp;
            }
        }

    });
    result['range'] = range
    result['rates'] = rates
    result['thresholds'] = thresholds       

});
</script>    

0 个答案:

没有答案