The first step is to introduce jquery files, either online or offline, to add to your own staticfiles
What's demonstrated here is adding offline
<script src={% static 'js/jquery-2.1.1.min.js' %}></script>
Note that this sentence is added before the ajax jquery script you write.
Then the HTML form is as follows:
- <form id="sqlform" method="post">
- {% csrf_token %}//Prevent Request Forgery
- <input id="sqlinput" name="sqlinputname" style="width:95%;height:30px;background-color:#fefcff; border:#d1d0ce 1px solid;" type="text"></input>
- <button id="submit" style="width:50px;height:30px;" type="submit" >query</button>
- </form>
- <pre id="sql_output" style="width:95%;margin-top:10px;height:100%;background-color:#fefcff; border:#d1d0ce 1px solid;" ></pre>
'django.middleware.csrf.CsrfViewMiddleware',
You need to add this sentence to your jquery.
$.ajaxSetup({ data: }' }, });Then the whole ajax script, the comparison written here is simply to highlight the communication with django:
- <script>
- $(document).ready(function(){
- $.ajaxSetup({
- data: }' },
- });
- $('#sqlform').submit(function(){
- var input = $("#sql input').val (); * get the user input sql statement in the form Note that it is the same as the input id in your html.
- $.ajax({
- type:"POST",
- data: ,
- url: "", //The url of the background processing function is used here. The static url needs to beUrls.pyName in or write http address directly
- cache: false,
- dataType: "html",
- success: function(ret){ <span style="font-family: Roboto, Helvetica, Arial, sans-serif;">//Pop up the result from view on success, which is the return value of HttpResponse in the back-end processing function</span>
- $('#sql_output').html(ret)
- // var content= $("#sqlinput");
- // $('#sql_output').append(content.val());
- },
- error: function(){
- alert("false");
- }
- });
- return false;
- });
- });
- </script>
Next, write about our backendView.pyBackend handler in
def comments_upload(request): if request.method == 'POST': print "it's a test" #For testing print request.POST['input'] #Test if you can receive an input field from the front end return HttpResponse(<span style="line-height: 1.42857;">request.POST['input']</span><span style="line-height: 1.42857;">) #Last Return to Front End </span> else: return HttpResponse("<h1>test</h1>")Because there is Chinese soViews.py Begin with
#coding=utf8Note: The url page of ajax POST is not the page that receives input.....I've slaughtered this place a second time...That is comments_The upload function is the processing function for the page of the POST request, and the page we submit the request (HTML above) is only the page that provides the input and receives the processing result, so the receive processing statement cannot be written in the HTML above, it needs to be written to comments_The page where the upload function is located.