Related free learning recommendations: ajax tutorial (video)
AJAX preparation knowledge: JSON
What is JSON?
JSON refers to JavaScript Object Notation
JSON is a lightweight text data exchange format
JSON is language independent*
JSON is self-describing and easier to understand
* JSON uses JavaScript syntax to describe data objects, but JSON remains language and platform independent. JSON parsers and JSON libraries support many different programming languages.
Qualified json object:
["one","two","three"]{"one":1,"two":2,"three":3}{"names":["张三","李四"]}[{"name":"张三"},{"name":"李四"}]
Unqualified json object:
{name:"张三",'age':32}//属性名必须使用双引号[32,64,128,0xFFF]//不能使用十六进制值{"name":"张三","age":undefined}//不能使用undefined{"name":"张三","birthday":newDate('Fri,26Aug201107:13:10GMT'),"getName":function(){returnthis.name;}//不能使用函数和日期对象}
stringify and parse method
About in JavaScript Two methods for JSON object and string conversion:
JSON.parse(): used to convert a JSON string into a JavaScript object
JSON.parse('{"name":"Q1mi"}'); JSON.parse('{name:"Q1mi"}') ; // 错误 JSON.parse('[18,undefined]') ; // 错误
JSON.stringify(): used to convert JavaScript values are converted to JSON strings.
JSON.stringify({"name":"Q1mi"})
Comparison with XML
The JSON format was proposed by Douglas Crockford in 2001, with the purpose of replacing the cumbersome and cumbersome XML format.
The JSON format has two significant advantages: it is simple to write and clear at a glance; it conforms to the native JavaScript syntax and can be directly processed by the interpretation engine without adding additional parsing code. Therefore, JSON was quickly accepted and has become the standard format for major websites to exchange data. It was written into ECMAScript 5 and became part of the standard.
XML and JSON both use structured methods to mark data. Let’s make a simple comparison below.
The data of some provinces and cities in China are expressed in XML as follows:
<?xml version="1.0" encoding="utf-8"?><country><name>中国</name><province><name>黑龙江</name><cities><city>哈尔滨</city><city>大庆</city></cities></province><province><name>广东</name><cities><city>广州</city><city>深圳</city><city>珠海</city></cities></province><province><name>台湾</name><cities><city>台北</city><city>高雄</city></cities></province><province><name>新疆</name><cities><city>乌鲁木齐</city></cities></province></country>XML格式数据
XML format data
The data in JSON is expressed as follows:
{"name":"中国","province":[{"name":"黑龙江","cities":{"city":["哈尔滨","大庆"]}},{"name":"广东","cities":{"city":["广州","深圳","珠海"]}},{"name":"台湾","cities":{"city":["台北","高雄"]}},{"name":"新疆","cities":{"city":["乌鲁木齐"]}}]}JSON格式数据
JSON format data
As can be seen from the above two-end code, JSON's simple syntax format and clear hierarchical structure are obviously easier to read than XML, and in terms of data exchange, since JSON uses much fewer characters than XML, it can Greatly save the bandwidth occupied by transmitting data.
Introduction to AJAX
AJAX (Asynchronous Javascript And XML) is translated into Chinese as "asynchronous Javascript and XML". That is, Javascript language is used to interact asynchronously with the server, and the data transmitted is XML (of course, the data transmitted is not just XML).
AJAX is not a new programming language, but a new way of using existing standards.
The biggest advantage of AJAX is that it can exchange data with the server and update part of the web page content without reloading the entire page. (This feature gives users the feeling of completing the request and response process unconsciously)
AJAX does not require any browser plug-ins, but requires the user to allow JavaScript to execute on the browser.
Synchronous interaction: After the client sends a request, it needs to wait for the server response to complete before sending a second request;
Asynchronous interaction : After the client issues a request, it can issue a second request without waiting for the server response to complete.
Example
The page inputs two integers, transmits them to the backend through AJAX, calculates the result and returns it.
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="x-ua-compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1"><title>AJAX局部刷新实例</title></head><body><inputtype="text"id="i1">+<inputtype="text"id="i2">=<inputtype="text"id="i3"><inputtype="button"value="AJAX提交"id="b1"><scriptsrc="/static/jquery-3.2.1.min.js"></script><script>$("#b1").on("click",function(){$.ajax({url:"/ajax_add/",type:"GET",data:{"i1":$("#i1").val(),"i2":$("#i2").val()},success:function(data){$("#i3").val(data);}})})</script></body></html>HTML部分代码
HTML partial code
def ajax_demo1(request): return render(request, "ajax_demo1.html") def ajax_add(request): i1 = int(request.GET.get("i1")) i2 = int(request.GET.get("i2")) ret = i1 + i2 return JsonResponse(ret, safe=False) views.py views.py rlpatterns = [ ... url(r'^ajax_add/', views.ajax_add), url(r'^ajax_demo1/', views.ajax_demo1), ... ] urls.py
AJAX common application scenarios
The search engine automatically prompts to retrieve keywords based on the keywords entered by the user. .
Another very important application scenario is the checking of user names during registration.
In fact, AJAX technology is used here! When the input in the file box changes, use AJAX technology to send a request to the server, and then the server will respond to the query results to the browser, and finally display the results returned by the backend.
The page is not refreshed during the whole process, it is just a partial refresh of the page!
After the request is sent, the browser can also perform other operations without waiting for the server's response!
After entering the user name and moving the cursor to other form items, the browser will use AJAX technology to make a request to the server. The server will query whether the user named lemontree7777777 exists. Finally, the server returns true to indicate the name. The user lemontree7777777 already exists, and the browser displays "The username has been registered!" after getting the result.
The page is not refreshed during the entire process, only partially refreshed;
After the request is issued, the browser can perform other operations without waiting for the server response result;
Advantages and disadvantages of AJAX
Advantages:
AJAX uses JavaScript technology to send asynchronous requests to the server;
AJAX requests do not require refreshing the entire page ;
Because the server response content is no longer the entire page, but part of the page, AJAX performance is high;
AJAX implemented by jQuery
The most basic example of jQuery sending an AJAX request:
<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><metahttp-equiv="x-ua-compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1"><title>ajaxtest</title><scriptsrc="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script></head><body><buttonid="ajaxTest">AJAX测试</button><script>$("#ajaxTest").click(function(){$.ajax({ url:"/ajax_test/", type:"POST", data:{username:"Q1mi",password:123456}, success:function(data){alert(data)}})})</script></body></html>
views.py:
def ajax_test(request): user_name = request.POST.get("username") password = request.POST.get("password") print(user_name, password) return HttpResponse("OK")
$.ajax parameters
data参数中的键值对,如果值值不为字符串,需要将其转换成字符串类型。
defajax_test(request):user_name=request.POST.get("username")password=request.POST.get("password")print(user_name,password)returnHttpResponse("OK")
JS实现AJAX
varb2=document.getElementById("b2");b2.onclick=function(){// 原生JSvarxmlHttp=newXMLHttpRequest();xmlHttp.open("POST","/ajax_test/",true);xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlHttp.send("username=q1mi&password=123456");xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState===4&&xmlHttp.status===200){alert(xmlHttp.responseText);}};};
AJAX请求如何设置csrf_token
方式1
通过获取隐藏的input标签中的csrfmiddlewaretoken值,放置在data中发送。
$.ajax({ url:"/cookie_ajax/", type:"POST", data:{"username":"Q1mi","password":123456,"csrfmiddlewaretoken": $("[name = 'csrfmiddlewaretoken']").val()// 使用jQuery取出csrfmiddlewaretoken的值,拼接到data中}, success:function(data){console.log(data);}})
方式2
通过获取返回的cookie中的字符串 放置在请求头中发送。
注意:需要引入一个jquery.cookie.js插件。
$.ajax({ url:"/cookie_ajax/", type:"POST", headers: {"X-CSRFToken":$.cookie('csrftoken')},// 从Cookie取csrftoken,并设置到请求头中data:{"username":"Q1mi","password":123456}, success:function(data){console.log(data);}})
或者用自己写一个getCookie方法:
functiongetCookie(name){varcookieValue=null;if(document.cookie&&document.cookie!==''){varcookies=document.cookie.split(';');for(vari=0;i<cookies.length;i++){varcookie=jQuery.trim(cookies[i]);// Does this cookie string begin with the name we want?if(cookie.substring(0,name.length+1)===(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}returncookieValue;}varcsrftoken=getCookie('csrftoken');
每一次都这么写太麻烦了,可以使用$.ajaxSetup()方法为ajax请求统一设置。
注意:
如果使用从cookie中取csrftoken的方式,需要确保cookie存在csrftoken值。functioncsrfSafeMethod(method){// these HTTP
methods do not require CSRF protectionreturn(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}$.ajaxSetup({ beforeSend:function(xhr,settings){if(!csrfSafeMethod(settings.type)&&!this.crossDomain){xhr.setRequestHeader("X-CSRFToken",csrftoken);}}});
如果你的视图渲染的HTML文件中没有包含 {% csrf_token %},Django可能不会设置CSRFtoken的cookie。
这个时候需要使用ensure_csrf_cookie()装饰器强制设置Cookie。
django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def login(request): pass
更多细节详见:Djagno官方文档中关于CSRF的内容
AJAX上传文件
XMLHttpRequest 是一个浏览器接口,通过它,我们可以使得 Javascript 进行 HTTP (S) 通信。XMLHttpRequest 在现在浏览器中是一种常用的前后台交互数据的方式。2008年 2 月,XMLHttpRequest Level 2 草案提出来了,相对于上一代,它有一些新的特性,其中 FormData 就是 XMLHttpRequest Level 2 新增的一个对象,利用它来提交表单、模拟表单提交,当然最大的优势就是可以上传二进制文件。下面就具体
首先看一下formData的基本用法:FormData对象,可以把所有表单元素的name与value组成一个queryString,提交到后台。只需要把 form 表单作为参数传入 FormData 构造函数即可:
介绍一下如何利用 FormData 来上传文件。
django.views.decorators.csrfimportensure_csrf_cookie@ensure_csrf_cookiedeflogin(request):pass
或者使用
var form = document.getElementById("form1"); var fd = new FormData(form);
这样也可以直接通过ajax 的 send() 方法将 fd 发送到后台。
注意:由于 FormData 是 XMLHttpRequest Level 2 新增的接口,现在 低于IE10 的IE浏览器不支持 FormData。
练习(用户名是否已被注册)
功能介绍
在注册表单中,当用户填写了用户名后,把光标移开后,会自动向服务器发送异步请求。服务器返回这个用户名是否已经被注册过。
案例分析
页面中给出注册表单;
在username input标签中绑定onblur事件处理函数。
当input标签失去焦点后获取 username表单字段的值,向服务端发送AJAX请求;
django的视图函数中处理该请求,获取username值,判断该用户在数据库中是否被注册,如果被注册了就返回“该用户已被注册”,否则响应“该用户名可以注册”。
序列化
Django内置的serializers
def books_json(request): book_list = models.Book.objects.all()[0:10] from django.core import serializers ret = serializers.serialize("json", book_list) return HttpResponse(ret)
The above is the detailed content of Examples to explain the implementation of AJAX with jQuery and JS. For more information, please follow other related articles on the PHP Chinese website!