django jquery.ajax()和json加载动态图像

时间:2019-01-08 09:18:05

标签: jquery json ajax django image

我正在尝试在Django中使用JSON,jquery,ajax来动态加载图像。

我没有了解Django。我搜索了stackoverflow,然后复制并粘贴了我所理解的内容。所以我不太了解Django。而且很少有例子。为此,我问一个问题。

没有错误。但这不起作用。我不知道在Django中如何工作。我该怎么解决

survey.html

password_toggle_imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (et_input_pass.getTransformationMethod().getClass().getSimpleName() .equals("PasswordTransformationMethod")) {
            et_input_pass.setTransformationMethod(new SingleLineTransformationMethod());
        }
        else {
            et_input_pass.setTransformationMethod(new PasswordTransformationMethod());
        }

        et_input_pass.setSelection(et_input_pass.getText().length());
    }
});

views.py

<script type="text/javascript">

    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            startLoadFile();
        }
    };

    function startLoadFile() {
        $.ajax({
            url: '/static/polls/json/images.json',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                createImages(data)
            }
        })
    }

    function createImages(objImageInfo) {
        var images = objImageInfo.images;
        var strDOM = "";

        var image = images[0];
        var image1 = images[1]; 

        strDOM += '    ';
        strDOM += '<img src="' + image.url + '" ';
        strDOM += 'class="wheel-first" width="135" height="135" />'
        strDOM += '    ';
        strDOM += '<img src="' + image1.url + '" ';
        strDOM += 'class="wheel-second" width="135" height="135" />'


        var $imageContainer = $("#wheels-img-container");
        $imageContainer.append(strDOM);
    }

</script>

<div class="wheels-img-container"></div>

images.json

from django.shortcuts import render
from django.views.generic import DetailView
from polls.models import Wheel
from django.core import serializers

def survey(request):
    json_serializer = serializers.get_serializer("json")()
    wheels = json_serializer.serialize(Wheel.objects.all(), ensure_ascii=False)
    return render(request, 'polls/survey.html', {'wheels' : wheels})

0 个答案:

没有答案