Home  >  Article  >  Web Front-end  >  How to use the ajax post method in the Django framework

How to use the ajax post method in the Django framework

亚连
亚连Original
2018-05-25 09:42:292934browse

Django is an open source web application framework, written in Python. This article introduces how the Django framework uses the ajax post method. Interested friends should come and learn together.

Django is an open source web application framework. Source code web application framework, written in Python. The MVC software design pattern is adopted, namely model M, view V and controller C. It was originally developed to manage some of the news content-based websites of Lawrence Publishing Group, that is, CMS (Content Management System) software. And was released under the BSD license in July 2005. This frame is named after the Belgian gypsy jazz guitarist Django Reinhardt.

Today I found a problem when trying to call jQuery's ajax. The server can return normally using the GET method, but not the POST method. Later, testing the form-based POST method also didn't work. As long as POST will report HTTP 403 error! very strange. . .

After searching a lot of information on the Internet, it turns out that it is due to a problem with Django's Cross Site Request Forgery protection mechanism. This mechanism is to protect against CSRF attacks. What is a crsf attack? Taolin blog has a relatively simple explanation. Solution Django's official website has provided http://docs.djangoproject.com/en/dev/ref/contrib/csrf/. After modification according to the instructions, ajax can be posted smoothly.

The specific method is to first solve the POST of the form. Find MIDDLEWARE_CLASSES in the settings.py file and add a middleware: 'django.middleware.csrf.CsrfViewMiddleware'. The modified code is as follows:

Python code

MIDDLEWARE_CLASSES = ( 
 'django.middleware.common.CommonMiddleware', 
 'django.contrib.sessions.middleware.SessionMiddleware', 
 'django.middleware.csrf.CsrfViewMiddleware', 
 'django.contrib.auth.middleware.AuthenticationMiddleware', 
 'django.contrib.messages.middleware.MessageMiddleware', 
 'django.middleware.csrf.CsrfResponseMiddleware', #加入这个中间件 
)


After this modification, the problem of HTTP 403 submission via form POST can be solved. Just changing the Post submission of ajax in this way is not enough. You also need to hook up a cookie processing process for each submission. That is, every time you submit, this process is triggered and the csrf token is added to the submitted http header. Fortunately, if you use jQuery to handle ajax, Django directly sends a piece of code to solve the problem. Put it in a separate js file and introduce it in the html page. Note that this js file must be imported after the jquery js file is imported. I copied the code directly, as follows:

Js code

##

$('html').ajaxSend(function(event, xhr, settings) { 
 function getCookie(name) { 
  var cookieValue = null; 
  if (document.cookie && document.cookie != '') { 
   var cookies = document.cookie.split(';'); 
   for (var i = 0; i < cookies.length; i++) { 
    var cookie = jQuery.trim(cookies[i]); 
    // Does this cookie string begin with the name we want? 
    if (cookie.substring(0, name.length + 1) == (name + &#39;=&#39;)) { 
     cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 
     break; 
    } 
   } 
  } 
  return cookieValue; 
 } 
 if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { 
  // Only send the token to relative URLs i.e. locally. 
  xhr.setRequestHeader("X-CSRFToken", getCookie(&#39;csrftoken&#39;)); 
 } 
});

After this After a lot of trouble, I can finally use ajax to communicate with Django normally.

Usage of ajax in Django

The front-end ajax code is as follows:

$.ajax({
 type:&#39;GET&#39;,
 url:&#39;/store/ds_mgmt_wx/ajax_handle&#39;,
 dataType:&#39;html&#39;,
 success:function(data)
  {
   alert(data);
  },
 error:function(data)
 {
  alert(data); 
 }
});

The return method of the corresponding code on the backend is as follows:

if act_job == &#39;ajax_handle&#39;:
  return HttpResponse(&#39;ajax_handle&#39;)

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed explanation of ajax jtemplate to implement dynamic paging

A simple implementation of Ajax showing progress during the request process

JQuery Ajax dynamically generates Table

##

The above is the detailed content of How to use the ajax post method in the Django framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn