The Ajax explanations in Django

Source: Internet
Author: User

AJAX (Asynchronous JavaScript and XML) is translated into Chinese as "Asynchronous JavaScript and XML." Even if you interact asynchronously with the server in JavaScript, the data transferred is XML (of course, the data transferred is not just XML).

Synchronous interaction: After a client makes a request, it needs to wait for the server response to complete before issuing a second request;
Asynchronous interaction: After a client makes a request, it can issue a second request without waiting for the server response to end.
Ajax in addition to the characteristics of asynchronous, there is a: Browser page local refresh, (this feature to the user's feelings is unknowingly completed the request and response process)

I.AJAX Common Application Scenarios

When we enter an "old " word in Baidu , a drop-down list will appear immediately! The list shows 4 keywords that contain a " pass " word .

In fact, this is the use of AJAX technology! When the file box changes in input, the browser uses AJAX technology to send a request to the server, querying the first ten keywords that contain the word "pass " . The server then responds to the query to the browser, and the browser displays the 4 keywords in a drop- down list.

    • The whole process of the page is not refreshed, just refresh the local location of the page!
    • When the request is issued, the browser can do other things without waiting for the server to respond!

When the user name is entered and the cursor is moved to a different form item, the browser uses AJAX technology to make a request to the server that queries whether the user named Zhangsan exists and the final server returns true Indicates that a user named lemontree7777777 already exists, and the browser shows "user name has been registered" after getting results ! ".

    • The whole process of the page is not refreshed, just local refresh;
    • After the request is issued, the browser can do other things without waiting for the server to respond to the result;
Advantages:
    • AJAX uses Javascript technology to send asynchronous requests to the server;
    • AJAX does not need to refresh the entire page;
    • Because the server response content is no longer the entire page, but the local part of the page, AJAX performance is high;

Two. $.ajax parameters

Let's start by looking at a common example of an AJAX request that uses Ajax to send a "like" Request:

$ (document). Ready (function () {$ (". Diggit"). Click (function () {//send the current article_id to the server, whether you like or step out: is_up//now that we want to send the article ID, we need to create a new tag in article_detail.html and then use it to store the article ID .//first, you need to determine if the user has logged in//<div class= "info" article_id= "{{Article_detail_obj.article.nid}}" User_name= "{{Article_detail_ Obj.article.user.username}} "></div>//if the custom attribute user_name has a value that means that the user is logged in, I send the AJAX request directly    if($(". Info"). attr ("user_name") {$.ajax ({URL:"/users/up_down/", type:"Post", data: {is_up:"True", article_id: $ (". Info"). attr ("article_id"), Csrfmiddlewaretoken: $ ("input[name= ' Csrfmiddlewaretoken ']"). Val ()}, Success:function (data) {//Up_down_response = {"Status": True, "Is_repeat": None}//judge the status state, true to praise the success, then the current point like +1, and print a message like successConsole.log (data);//{status:false, is_repeat:true}                if(data.status) {Current_up_count= parseint ($ ("#digg_count"). text ()); Current_up_count+=1; $("#digg_count"). HTML (current_up_count); SetTimeout (function () {$ (". Dig_message"). HTML ("Congratulations on your great success."). CSS ("Color","Red")                    },  the)                }                Else if(data.is_repeat) {setTimeout () (function () {$ (". Dig_message"). HTML ("Sorry, I can't repeat it."). CSS ("Color","Red")                    },  the)                }            }        })    }    //user not logged in    Else{console.log (location.pathname);//got the path part.setTimeout (function () {$ (". Dig_message"). HTML ("Sorry, you have not logged in, can not be like, 3 seconds later will jump to the login page"). CSS ("Color","Red")        },  the); Location.href="/login/?next="+( location.pathname});});

Request parameters for "01" $.ajax

######################------------Data---------################ Data: The current AJAX request is to carry the information, is a JSON object, that is, a JSON object Ajax method will default to encode it into some form (urlencoded:? a=1&b=2) is sent to the server, and Ajax sends the request by default in the Get mode. function TestData () {$.ajax ("/test",{//the data at this point is a JSON-form objectdata:{A:1, B:2                  }               }); //? a=1&b=2######################------------ProcessData---------############### #processData: Declares whether the current data is transcoded or preprocessed, the default is true, which is preprocessing, and if set to False, then Data:{a:1B:2The ToString () method of the JSON object is called, which is {a:1B:2}.tostring () and finally get a [Object, Object] As the result of the form. ######################------------ContentType---------############### #contentType: Default value:"application/x-www-form-urlencoded". The content encoding type when sending information to the server. That is, tell the server that the data encoding format that my client uses is urlencoded:urlencoded:? a=1&b=2if you want to submit data in other ways, such as ContentType:"Application/json", that is, the client tells the server that I am sending a JSON string: Be sure to note that once the ContentType is set:"Application/json", then the data that we send to the server must be a JSON string, not a JSON object, or it will get an error, which is why we need to use json.stringify to serialize the JSON object to a JSON string! $.ajax ("/ajax_get", {data:JSON.stringify ({a: A, B: -}), ContentType:"Application/json", type:"POST",                            }); //{a:22, b:33}when the client sets the JSON string that I send to the server, the server will need to deserialize the data into a Python string note at this point, if we set the client to use post mode to send, Then we should take the data from the request body when we fetch the data from the server: Request.body.decode ("UTF8"), take out a byte string, and use Json.loads to deserialize the object in Python views.py:json.loads (Request.body.decode ("UTF8"))######################------------Traditional---------############### #traditional: It is generally used when we have arrays of data: Data:{a: AB: -, c:["x","y" ]}, traditional is false to make a deep iteration of the data; 

Response parameter: DataType

DataType function: Set the contents of the "Accept" field in the Httpheader, tell the server browser what type of data format you want to return, and jquery will format the returned data according to that type, for example, the value of client setting datatype is: "JSON", which means I tell the server that the data you return to me must be a JSON-formatted string,

Once the server returns me the JSON string, I can use it directly, because jquery will automatically convert the JSON string to a JS object without us having to convert it manually: Json.parse ()

The above is the Ajax knowledge of Django, the author will be in the next blog in detail about Ajax and form serialization related knowledge.

Reference URL: http://blog.csdn.net/walkerjong/article/details/7520485

The Ajax explanations in Django

Related Article

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.