【发布时间】:2021-03-26 10:23:12
【问题描述】:
当我点击按钮时,我得到了正确的控制台输出;但我的选择没有得到更新。请帮助我,因为我是 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
【问题讨论】:
-
该响应数据中没有
label或value属性。使用适当的键名 -
也不能将选项附加到另一个选项。选择器应该只是用于选择