【发布时间】:2017-06-20 22:46:53
【问题描述】:
在我的 django 项目中,我为动态显示和填充字段进行了 ajax 调用。 首先,在我的模板中我创建了元素:
模板 html
<select class="form-control" onChange="AddOptions(this);">
{% for entry in all_test %}
<option id="mainID" value="{{ entry.id }}">{{ entry.descr }}</option>
{% endfor %}
</select>
<div id = "div_val" class="input-group" style="display: none;">
<div class="input-group-btn">
<button id = "btn_val" type="button" class="btn btn-danger">Test</button>
</div><!-- /btn-group -->
<input type="text" class="form-control">
</div>
然后在我的 js 中:
start.js
function AddOptions(VarID) {
$.ajax({
type: "POST",
url: "ajax",
data: {mainID: VarID.value},
success: function (data) {
$.each(data, function (index) {
$("#div_val").show();
console.log("Key: " + data[index].OptionKey+" Val: "+ data[index].OptionVal)
});
}
});
}
urls.py
url(r'^ajax$', mainoptions),
最后是我从 urls.py 调用的 python 函数:
from frontend.models import temp_main, temp_case, temp_variables
def mainoptions(request):
if request.is_ajax():
mainOptions = temp_variables.objects.filter(main_id=int(request.POST['mainID']))
response = []
for i in mainOptions:
vallabel = {}
vallabel['OptionID'] = i.id
vallabel['OptionKey'] = i.v_key
vallabel['OptionVal'] = i.v_val
response.append(vallabel)
json = simplejson.dumps(response)
return HttpResponse(
json, content_type='application/json'
)
else:
pass
全部完成,我在模板中隐藏的 div“div_val”已显示,但现在我无法理解如何在模板中使用返回的数据,例如,填充 div 内元素的值(无需在我的 js func 中使用 jquery 即可)。 如何关闭链模板 -> js -> urls -> 查看方法 -> 模板?
提前致谢
【问题讨论】:
标签: javascript jquery python ajax django