我正在尝试使用 AJAX,其中客户端从下拉列表中选择一个州,然后该州内的县将出现在下一个下拉列表中。
以下是 2 个模型:
class State(models.Model):
state = models.CharField(max_length=150)
population = models.IntegerField(default=None
def __str__(self):
return self.state
class County(models.Model):
state = models.ForeignKey(State,on_delete=models.CASCADE)
county = models.CharField(max_length=150)
population = models.IntegerField(default=None)
def __str__(self):
return self.county + " County," + str(self.state)
以下是我的观点:
def home(request):
states = State.objects.all()
return render(request,'api/home.html',{'states': states})
def load_counties(request):
state = request.GET.get('SelectedState')
chosen_state_id = State.objects.get(state=state).__dict__['id']
query = County.objects.filter(state=chosen_state_id)
context = serialize('json',query)
return HttpResponse(context,content_type="application/json")
我在 load_counties 视图中的“上下文”变量返回 <QuerySet [<County: Johnson County,Kansas>,<County: Douglas County,<County: Miami County,Kansas>]>
我遇到的错误是当前我的浏览器在浏览器控制台中返回 [{"model":"api.county","pk":6,"fields":{"state":3,"county":"Johnson","population":602000}},{"model":"api.county","pk":9,"county":"Douglas","population":122259}},"pk":10,"county":"Miami","population":34237}}]
。
这里也是我的 HTML
<!--SELECT STATE-->
<label for="states">Choose a State:</label>
<select name="state" id="states">
<option value="select">Select...</option>
{% for state in states %}
<option value="{{ state }}">{{ state }}</option>
{% endfor %}
</select>
<br><br>
<!--SELECT COUNTY-->
<br><br>
<label for="county">Choose a County:</label>
<select name="county" id="county">
<option value="choose">Choose...</option>
{% for county in counties %}
<option value="{{ county }}">{{ county }}</option>
{% endfor %}
</select>
<script>
// $(document).ready(function(){
// jQuery methods go here...
$("#states").change(function () {
var selectedState = $(this).find("option:selected").text(); //or .val()??
var selectedValue = $(this).val();
// alert("Selected Text: " + selectedText + " Value: " + selectedValue);
// create an AJAX call
$.ajax({
data: {
'SelectedState': selectedState
},// get the form data
type: 'GET',// GET or POST
url: "{% url 'ajax_load_counties' %}",dataType: 'JSON',// on success
success: function (counties) {
if (counties) {
// var dataCounty = document.getElementById('selectedCounties');
// var jsonString = JSON.parse(counties)
console.log(JSON.stringify(counties));
// var names = counties;
// $("h2").each(counties,function (index,value){
// console.log("Array Current Index is: "+ index + " :: Value is: " + value);
// });
};
},// on error
error: function (counties) {
// alert the error if any error occured
alert(response.responseJSON.errors);
console.log(response.responseJSON.errors)
}
});
return false;
});
//});
</script>