首页 > 解决方案 > 如何从 Jquery Ajax 成功数据中更新选择选项

问题描述

当我单击按钮时,我得到了正确的控制台输出;但我的选择没有得到更新。请帮助我,因为我是 Ajax、Jquery 和 Django 的新手。我花了一个多星期来解决这些问题。但没有结果。

我的 Django 代码:

# model
class Post(models.Model):
    post_heading = models.CharField(max_length=200)
    post_text = models.TextField()

    def __str__(self):
        return self.post_heading

# view
def getmydata(request):
    # get the provinces for given country from the
    # database excluding null and blank values

    if request.method == "GET" :
       data = list(Post.objects.all().values())
       return JsonResponse({"data": data})

我的html模板是:

    <div >
        <select name="car_maker" id="car_maker">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="fiat">Fiat</option>
            <option value="audi">Audi</option>
        </select>
    </div>
    <div class="postacct">
        <p>>{{ acct.post_heading }}</p>>
        </div>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript">
    $('.clickme').click(function(){
        let catid;
        {#catid = $(this).attr("data-catid");#}
        catid='nil'
    $.ajax(
        {
            type: "GET",
            url: "/getmydata",
            data: {
                post_id: catid,
                'csrfmiddlewaretoken': '{{csrf_token}}'
            },
            success: function (data) {

                
                console.log(data);
                $("#car_maker option").remove();

                $.each(data.rows, function (index, item) { //jQuery way of iterating through a collection
                    $("#car_maker option").append($('<option>')
                        .text(item.label)
                        .attr('value', item.value));
                })
            }
        })})
    </script>
    </body>
    </html>

从 ajax 我得到控制台输出:

(index):54 

{data: Array(2)}

data: Array(2)s
0: {id: 1, post_heading: "2", post_text: "two"}
1: {id: 2, post_heading: "1", post_text: "one"}
length: 2

标签: jquerydjangoajax

解决方案


I tried to reconstruct your code.

<select name="car_maker" id="car_maker">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="fiat">Fiat</option>
  <option value="audi">Audi</option>
</select>

With your response

var data = {
  "data": [{
    'id': 1,
    'post_heading': '2',
    'post_text': 'two'
  }, {
    'id': 2,
    'post_heading': '1',
    'post_text': 'one'

  }]
}

console.log(data);

$("#car_maker option").remove();

$.each(data, function(index, item) {
  console.log('test', item[0].post_heading);
  console.log('test', item[1].post_text);
  $.each(item, function(index1, item1) {
    console.log(item1.id);
    console.log(item1.post_heading);
    console.log(item1.post_text);
    $('#car_maker').append($('<option/>', {
      value: item1.id,
      text: item1.post_text
    }));
  })
});

推荐阅读