Django uses jquery Ajax to submit form implementation to refresh some pages

Source: Internet
Author: User

First of all to introduce jquery files, can be introduced online, you can also download offline add to their own staticfiles

The demo here is to add the offline

<script src={% static ' Jquery/jquery.min.js '%}></script>
Note that this sentence is to be added to the front of the jquery script that you wrote

And then write a simple form.


<form method= "POST" id= "Formadd" >        {% csrf_token%}        <label for= "id_name" > User name </label>        <input type= "text" id= "Id_name"/>        <label for = "Id_password" > Password </label>        <input type= " Password "id=" Id_password "/>        <button type=" Submit "id=" submit "> Submit </button>    </form>

A simple form with a single user name and password and a submit button note I'm here for the form ID is formadd looks very shabby ~


And then add our form-handled jquery

If you're not commenting out in Settings,

' Django.middleware.csrf.CsrfViewMiddleware ',

You need to add this in your jquery, details refer to the self-improvement academy Django Ajax CSRF

$.ajaxsetup ({                 data: {csrfmiddlewaretoken: ' {{csrf_token}} '},            });
And then the whole jquery script, where the comparison is written here is simply the main highlight of the communication with Django
<script src={% static ' Jquery/jquery.min.js '%}></script> <script> $ (document). Ready (Function (        {$.ajaxsetup ({data: {csrfmiddlewaretoken: ' {{csrf_token}} '},});                 $ (' #formadd '). Submit (function () {var name = $ ("#id_name"). Val ();    Get the name of the user input in the form note here the Id_name is consistent with the ID in your HTML var password = $ ("#id_password"). Val (); Ibid. $.ajax ({type: "POST", data: {name:name, Password:                    Password}, url: "{% url ' blog:comments_upload '%}",//the URL of the spooler function here is a static URL that needs to be consistent with name in urls.py Cache:false, DataType: "HTML", success:function (result, statues, X                                         ML) {alert (result); Error:function () {alert ("false") when the view returns the result of a successful popup.);                }                });            return false;        });    }); </script>
Next, we write back-end processing functions in our backend view.py.
def comments_upload (Request):    if Request.method = = ' POST ':        print ' It ' s a test '                            #用于测试        print request. post[' name ']           #测试是否能够接收到前端发来的name字段        print request. post[' password ']     #用途同上        return httpresponse ("form Test succeeded")     #最后返会给前端的数据, if we can show in the front-end popup box We have succeeded    else:        Return HttpResponse ("
Since there is Chinese so the views.py opening plus

#coding =utf8
Add one to the last urls.py (note that this is the urls.py in my app)

URL (r ' ^comments_upload/$ ', comments_upload, name= ' comments_upload '),
Then fire your server

Test

Starting development Server at Http://127.0.0.1:8000/Quit the server with control-c.it ' s a testtesttestpassword
The backend console successfully prints out our name and password fields

In fact, we can do a lot of things in this views.py, such as the name and password field to verify, or into the database, and then return a piece of real HTML code, the local replacement of the front page, to achieve the effect of asynchronous transmission


Django uses jquery Ajax to submit form implementation to refresh some pages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.