python - how we can use ajax() in views.py in django? -
I have a little code here.
Could you please tell me what this code really does? please.
Here in the AJAX call:
$ .ajax ({url: "{% url} upload_document '%}", type: "POST", data : {Csrfmiddletoken: document.getElementsByName ('csrfmiddletoken') [0] Price, Title: document.getElementById ('title'). Value, // document: document: document.getElementById ('document'),}, datatype: "Jason", success: function (feedback) {if (feedback == "true") {// success} other {// attachment errors}}}); How AJAX works in the Django and how we can see the AJAX request.
Here is the idea of my thoughts
def upload_document (requested): Print request. POTT print request FILES if request.is_ajax (): If request.method == 'POST': form = UploadForm (request.POST, request.FILES, user = request.user) if form.is_valid (): Form.save () return HTTPPCS (SimpleJason Dumps ('True'), Mime Type = 'App / Jason') Other: Errors = Form. Error Returns HTTPRPS section (SimpleJason Dumps (Errors), Mime Type = 'App / Jason Thanks in advance.
normal In the $ .ajax method sends an asynchronous HTTP request. You can read about it.
The first argument is url, where we request
The second is the request method, it can be found, posted, put, deleted and etc.
The third argument The key-value dictionary that you use in server-side. In the DNS, you can enter it in the request. POST (in the case of a post request)
The fourth argument is the function This is applicable when the server successfully answers if you do not need the statement in this function, because when the request fails or the server does not respond, or returns the error to the server (for example 40 * < / Code> This function will not be applied to anything. / P> This function takes an argument with the response of the server. You need to handle this data, for example, the user will be able to invalid data such as Showing messages, please correct errors ... or valid data Your request is now in process. and the employee of that kind. The last argument is server type data type. JQuery is smart enough to parse json or html for you, so the response in this case (logic of success function) is pure JS object, deserialized from JSON.
In your server side (Django view) you should verify some of the data of the request and do something with it. For example, save it in the database when I want to implement Ajax form processing, :
if request.method == 'POST': feedback = {} form = upload form (request .post, request.FILES, user = request.user) if form.is_valid ( ): Form.save () response ['success'] = 1 other: feedback [' success'] = 0 response [' Returns: 'HttpResponse' (simplejson.dumps (feedback), mime type = 'application / jsan') and on client side, something like that in JS P>
$ post ('/ url / to / view', function (json) {if (json ['success']) {Warning (' Yahoo! Success Request ')} Other {Warning (' Oooops. It seems you send invalid data ')}}},' Jason ') Good luck!
Comments
Post a Comment