在视图中创建JSON对象并在HTML

时间:2018-04-15 03:21:26

标签: javascript json django django-views

views.py - Django 2.0.2

def hotels(request):
    list_of_hotels = Hotel.objects.order_by('hotel_name')
    template = loader.get_template('myapp/hotels.html')

    data = {}
    for each in list_of_hotels:
        data[str(each.hotel_name)] = 'null'
    json_data = json.dumps(data)

    context = {
        'list_of_hotels': list_of_hotels,
        'json_data': json_data,
    }
    return HttpResponse(template.render(context, request))

hotels.html

<div class="row">
  <div class="col s12">
    <div class="row">
      <div class="input-field col s12">
        <i class="material-icons prefix">search</i>
        <input type="text" id="autocomplete-input" class="autocomplete">
        <label for="autocomplete-input">Search</label>
      </div>
    </div>
  </div>
</div>

<script>
  var jsonObj = "{{json_data}}";
  $(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: jsonObj,
    });
  });
</script>

我正在尝试将Django视图中的JSON对象解析为位于相应HTML页面内的脚本。我尝试了一切,但它似乎没有用。我现在搜索Stack Overflow大约一个小时,并根据所有答案来到这些代码片段,但仍然无法正常工作。任何关于如何去做的线索都将受到高度赞赏!

P.S:在hotels.html的脚本中,数据包含一个JSON对象。有关初始化的更多详细信息,请参阅this

P.P.S:我是JavaScript / jQuery中的绝对菜鸟。

1 个答案:

答案 0 :(得分:0)

经过多次尝试后找到了解决我自己问题的方法。感谢任何试图帮助我的人。 :)

<强> hotels.html

<div class="row">
 <div class="col s12">
  <div class="row">
   <div class="input-field col s12">
    <i class="material-icons prefix">search</i>
    <input type="text" id="autocomplete-input" class="autocomplete">
    <label for="autocomplete-input">Search</label>
   </div>
  </div>
 </div>
</div>

<script type='text/javascript'>
  var jsonObj = {{ json_data|safe }};
  $(document).ready(function(){
    $('input.autocomplete').autocomplete({
      data: jsonObj,
    });
  });
</script>

<强> views.py

def hotels(request):

    list_of_hotels = Hotel.objects.order_by('hotel_name')
    template = loader.get_template('myapp/hotels.html')

    data = {}
    for each in list_of_hotels:
        data[str(each.hotel_name)] = None
    json_data = json.dumps(data)

    context = {
        'list_of_hotels': list_of_hotels,
        'json_data': json_data,
    }
    return HttpResponse(template.render(context, request))