从django views.py获取数据并使用ajax显示它

Sta*_*iow 5 html django ajax jquery

EDITED

我正在尝试使用jquery/ajax来显示从django方法返回的数据.

我有一个名为keywordBtn的html按钮.因此,当按下它时,将调用updateKeywordSubscribed方法.

但是,我的目标不是由django返回的.我的方法有问题吗?

如果成功,div部分名称"update"将显示该json列表中的单词列表.

我的HTML中有什么:

<script type="text/javascript">
        $(document).ready(function() { 
            $("#keywordBtn").click(function(e) { 
                updateKeywordSubscribed(e, "#keywords"); 
            });
        });
        function updateKeywordSubscribed(e, keywords) {
            e.preventDefault();
            var option_form = jQuery(e.target);
            $.ajax({
                url : option_form.attr('action'),
                type : option_form.attr('method'),
                data : option_form.serialize(),
                dataType : 'json',
                success : function(response) { alert ('sometext')})
        }
</script>
Run Code Online (Sandbox Code Playgroud)

我在views.py中的内容:

def keyword_subscribe(request):
    if 'keyword_input' in request.POST:
    if 'name_input' in request.POST:
        xhr = request.GET.has_key('xhr')
        response_dict = {}
            new_keyword = request.POST['keyword_input']
        username = request.POST['name_input']
        response_dict.update({'keyword_input': new_keyword, 'name_input': username})
        power_keyword = subscribe_keyword(username,keywords)
        if power_keyword:
            response_dict.update({'success':True})
        else:
            response_dict.update({'errors':{}})
            if not username:
                        response_dict['errors'].update({'name_input': 'User ID is required'})
                if not total and total is not False:
                        response_dict['errors'].update({'keyword_input': 'Keyword field is blank'})
        if xhr:
                return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
            return render_to_response('r2/userprofile_list.html', response_dict)
Run Code Online (Sandbox Code Playgroud)

Fra*_*llo 13

我正在做一些类似于我当前项目所需要的东西.

我获取这个返回geojson结果的zipcode视图或null

我的看法:

def get_zipcode(request, latitude, longitude):
    # Point on a map
    point = GEOSGeometry('POINT(%s %s)' % (longitude, latitude))

    try :
        zipcodes = Zipcode.objects.filter(mpoly__contains=point)
        return HttpResponse(zipcodes[0].mpoly.geojson, mimetype="application/json")
    except :
        return HttpResponse(json.dumps(None), mimetype="application/json")
Run Code Online (Sandbox Code Playgroud)

我的mimetype是application/json而不是application/javascript

我的网址:

url(r'^collision/zipcode/(?P<latitude>(\-|)\d+\.\d+)/(?P<longitude>(\-|)\d+\.\d+)/', 'core.views.get_zipcode', name='collision-zipcode'),
Run Code Online (Sandbox Code Playgroud)

进行调用并处理json结果的JS

$.ajax({
    url : '/collision/zipcode/' + latitude + '/' + longitude + '/',
    dataType : 'json',
    type : 'GET',
    success: function(data)
    {
        var paths = coord_to_paths(data.coordinates); 
        var polygon = new google.maps.Polygon({ 
            paths : paths, 
            strokeColor : "#FF7800", 
            strokeOpacity : 1, 
            strokeWeight : 2, 
            fillColor : "#FF7800", 
            fillOpacity : 0.6
        });

        polygon.setMap(map);

        console.log("adding zipcode polygon");
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,如果您正在检索json,如果将dataType设置为'json',则应该将您的success函数中的数据作为JS本机访问.

如果你需要调试jquery实际检索的数据,请执行

console.log(data);
并在你的浏览器中查看我的浏览器(chrome/ff我不知道其他浏览器是否支持此功能)