将外部json数据加载到html表单中

时间:2018-01-30 10:55:49

标签: jquery html json forms

如何加载外部JSON文件?

注意:外部文件也可能被服务器设置阻止。

从本地JSON填写表单

<form id="datas-from-json">                        
    <div class="form-group">
        <label class="form-control">Name:</label>
        <input name="nameCustomer" class="form-control" type="text" autofocus>
        ...
    </div>
</form>

<script type="text/javascript">

  for(key in json) {
    if(json.hasOwnProperty(key))
      $('input[name='+key+']').val(json[key]);
  }

  // JSON
  var json={
    "nameCustomer": "Madmann",
    "surnameCustomer": "Max",
    "room": "32322",
    "telephone": "223231",
    "email": "info@blabla.com",
    "website": "www.blabla.com",
    "address": "Main Street 422",
    "sector": "1A"
  };

  </script>

从本地JSON文件中填写表单

$(document).ready( function() {  
  $.getJSON('data.json',
    function(data) {        
        for(key in data) {
          if(data.hasOwnProperty(key))
            $('input[name='+key+']').val(data[key]);
          }
    });
  });

从外部JSON文件中填写表单

$(document).ready( function() {  
  $.getJSON('http://www.example.net/data.json',
    function(data) {        
        for(key in data) {
          if(data.hasOwnProperty(key))
            $('input[name='+key+']').val(data[key]);
          }
    });
  });

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
  $.getJSON('folder/data.json',
    function(JSONdata) {
      for (key in JSONdata) {
        if (JSONdata.hasOwnProperty(key))
          $('input[name=' + key + ']').val(JSONdata[key]);
      }
    });
});

和自定义文件data.json(请参阅charlietfl的评论):

{
    "nameCustomer": "Madmann",
    "surnameCustomer": "Max",
    "room": "32322",
    "telephone": "223231",
    "email": "info@blabla.com",
    "website": "www.blabla.com",
    "address": "Main Street 422",
    "sector": "1A"
};

我认为我之间存在服务器问题,所以其他错误。