Ajax调用从django模板 [英] Ajax call from django template

查看:125
本文介绍了Ajax调用从django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django模板,它扩展了基础模板,该模板具有加载jquery的代码。这个模板有一个简单的文本框,我想通过ajax获取对象。

I have a django template which extends the base template that has code to load jquery in it. This template has a simple text box and I wanted to fetch the object through ajax.

{% extends 'base.html' %}
{% block content %}

<form id="ajaxform">
    <input type="text" name="first_name" id="name" />
    <input type="submit" value="Submit" />
</form>

<div id="dataDiv">

</div>

<script>
    $('#ajaxform').submit(function(){
        console.log('Form submitted');
        $.get('{% url get_ajax_data %}', $(this).serialize(),function(data){
            $('#dataDiv').text(data);

        })
        return false;
    });

</script>
{% endblock %}

在此模板中,我尝试使ajax调用get_ajax_data url,在相应的视图中,我简单地将文本返回为 return HttpResponse('Ajax respose')。但是,当我返回false时,这似乎不起作用,表单被提交。我不知道我错过了哪里。

In this template, I tried to make ajax call to the get_ajax_data url and in the corresponding view I simply returned text as return HttpResponse('Ajax respose'). But this does not seem to work and the form gets submitted while I have returned false. I am not sure where I missed.

推荐答案

通常的做法是初始化 submit()处理程序。这是通过在页面准备就绪时进行设置来完成的。目前您已经以正式的方式提交表单,甚至没有注册您的JavaScript。要解决它,你可以写:

Till was on to the answer, Common practice is to initialize the submit() handler. This is done by setting it when the page is ready. Currently you have it to submit the form the regular way, it's not even registering with your javascript. To fix it you could write:

$(document).ready(function() {
   $('#ajax_form').submit(fun // the rest of your code here.
});

这篇关于Ajax调用从django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆