How to update a div with an image in Django?

≯℡__Kan透↙ 提交于 2020-01-06 02:29:05

问题


The following is a matplotlib code that generates a scatter plot in as the response.

def plot(request):
    r = mlab.csv2rec('data.csv')
    fig = Figure(figsize=(6,6))          
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    ax.grid(True,linestyle='-',color='gray')
    ax.scatter(r.x,r.y);       
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

I would like to update a div tag in the template using jquery ajax. Following is the jquery code that listens to a form sumbit button and updates a div on success.

<script type="text/javascript" charset="utf-8">
    $(function() { 
        $('#plot').submit(function() {
          jQuery.ajax({            
            url: this.action,
            timeout: 2000,
            aysnc: true,
            error: function() {
              console.log("Failed to submit");
            },
            success: function(r) { 
              $('#plotarea').html(r);
              }
          }) 
            return false;
          })
     })
</script>

But when I click the submit button, junk characters are displayed on the div instead of the image.

Could any body guide me on how I could display the image from the response ?

Thanks in advance.


回答1:


It's failing because plot() outputs the raw image data (with headers) and you assign it directly to the contentarea (.html()) of the div. When the url returns the image data directly it should be used as the src attribute of an <img> tag instead.

If you don't wish to redesign your workflow you could try base64 encoding the string and use this method: http://www.websiteoptimization.com/speed/tweak/inline-images/

i.e. something like $('#image').attr('src', 'data:image/png;base64,' + r); in your success call.



来源:https://stackoverflow.com/questions/2212486/how-to-update-a-div-with-an-image-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!