Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何让Python字典用jQuery填充HTML选择选项?_Javascript_Jquery_Python_Django_Dictionary - Fatal编程技术网

Javascript 如何让Python字典用jQuery填充HTML选择选项?

Javascript 如何让Python字典用jQuery填充HTML选择选项?,javascript,jquery,python,django,dictionary,Javascript,Jquery,Python,Django,Dictionary,如果用户选择了一个#bundle,它会通过Ajax将请求发送到这个Django视图 @ensure_csrf_cookie def getcourses(request): if request.is_ajax(): id = int(request.POST['cat_id']) try: courses = Courses.objects.values('id', 'name').filter(cat_id = id)

如果用户选择了一个
#bundle
,它会通过Ajax将请求发送到这个Django视图

@ensure_csrf_cookie
def getcourses(request):
    if request.is_ajax():
        id = int(request.POST['cat_id'])
        try:
            courses = Courses.objects.values('id', 'name').filter(cat_id = id)
        except Courses.DoesNotExist:
            courses = None
        if courses:
            message = courses
            return HttpResponse(message)
        else:
            message = 'Please select a valid bundle...'
            return HttpResponse(message)
    else:
        return HttpResponseRedirect(reverse('mysite:index'))
该视图返回此字典:

{'id': 1L, 'name': u'Python'}
{'id': 2L, 'name': u'Django'}
{'id': 3L, 'name': u'jQuery'}
{'id': 4L, 'name': u'Ajax'}
我如何移除这些L

我想要的是在jQuery中迭代这个字典,并将它们作为HTML中
#courses
下的选项

<div class="control-group">
    <label class="control-label" for="selectbasic">Select a bundle...</label>
    <div class="controls">
        <select id="bundle" name="bundle" class="form-control input-xlarge">
            <option class = 'selected-value' value = '1'>Web Design</option>
            <option class = 'selected-value' value = '2'>Mobile Apps</option>
        </select>
        <select id="courses" name="courses" class="form-control input-xlarge">
        </select>
    </div>
</div>

选择一个包。。。
网页设计
移动应用
我的jQuery代码

$(document).on('change', '#bundle', function(){
    var $this = $( this );
    var $cat_id = $this.val()
    if ($cat_id.length > 0){
        var request = $.ajax({
          url: "/mysite/fetchcourses/",
          type: "POST",
          data: { cat_id : $cat_id },
          dataType: "html"
        });
        request.done(function( msg ) {
            $.each(msg, function (i, item) {
                $('#courses').append($('<option>', { 
                    value: item.id,
                    text : item.name 
                        }));
                    });
        });
        request.fail(function(XMLHttpRequest, textStatus, errorThrown){
            alert('errorThrown '+ errorThrown);
        })
    }
})
$(document).on('change','#bundle',function(){
var$this=$(this);
var$cat_id=$this.val()
如果($cat_id.length>0){
var请求=$.ajax({
url:“/mysite/fetchcourses/”,
类型:“POST”,
数据:{cat_id:$cat_id},
数据类型:“html”
});
request.done(函数(msg){
$。每个(消息、功能(i、项){
$('#课程')。附加($('',{
值:item.id,
text:item.name
}));
});
});
失败(函数(XMLHttpRequest、textStatus、errorshown){
警报(“错误抛出”+错误抛出);
})
}
})
如何迭代字典数据,并将其作为
#courses
下的选项?任何帮助都将不胜感激。

将其转换为json

import json 

... 

 if courses:
        message = list(courses)
        response =  HttpResponse(json.dumps(message), content_type ='application/json' )
        return response

现在,您可以将响应当作javascript对象来处理。

int()足以使1L->1。我尝试过这样做,但它说
Exception Type:TypeError at/mysite/fetchcourses/Exception Value:[{'id':1L,'name':u'Python'}..]JSON不可序列化
但它返回异常类型:AttributeError at/mysite/fetchcourses/Exception值:'NoneType'对象没有可能与csrf cookie有关的属性'set_cookie'。此视图中的表单发布是什么样子的?请原谅我的无知,表单发布的意思是指向视图的路径?是的。。。我的怀疑是,您不需要@sure_csrf_cookie decorator,您可以在模板中执行{%csrf_token%}