Home Web Front-end JS Tutorial Examples to explain the implementation of AJAX with jQuery and JS

Examples to explain the implementation of AJAX with jQuery and JS

Dec 08, 2020 pm 05:38 PM
ajax jquery

AJAX TutorialThe column example introduces the method of implementing AJAX with jQuery and JS

Examples to explain the implementation of AJAX with jQuery and JS

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":"李四"}]
Copy after login

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;}//不能使用函数和日期对象}
Copy after login

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]') ; // 错误
Copy after login

JSON.stringify(): used to convert JavaScript values ​​are converted to JSON strings.

JSON.stringify({"name":"Q1mi"})
Copy after login

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格式数据
Copy after login

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格式数据
Copy after login

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部分代码
Copy after login

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&#39;^ajax_add/&#39;, views.ajax_add),
    url(r&#39;^ajax_demo1/&#39;, views.ajax_demo1),
    ... 
]
urls.py
Copy after login

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>
Copy after login

views.py:

def ajax_test(request): user_name = request.POST.get("username") password = request.POST.get("password") print(user_name, password) return HttpResponse("OK")
Copy after login

$.ajax parameters

data参数中的键值对,如果值值不为字符串,需要将其转换成字符串类型。

defajax_test(request):user_name=request.POST.get("username")password=request.POST.get("password")print(user_name,password)returnHttpResponse("OK")
Copy after login

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);}};};
Copy after login

AJAX请求如何设置csrf_token

方式1

通过获取隐藏的input标签中的csrfmiddlewaretoken值,放置在data中发送。

$.ajax({  url:"/cookie_ajax/",  
type:"POST",  data:{"username":"Q1mi","password":123456,"csrfmiddlewaretoken":
$("[name = &#39;csrfmiddlewaretoken&#39;]").val()// 使用jQuery取出csrfmiddlewaretoken的值,拼接到data中},  success:function(data){console.log(data);}})
Copy after login

方式2

通过获取返回的cookie中的字符串 放置在请求头中发送。

注意:需要引入一个jquery.cookie.js插件。

$.ajax({  url:"/cookie_ajax/",  type:"POST",  headers:
{"X-CSRFToken":$.cookie(&#39;csrftoken&#39;)},// 从Cookie取csrftoken,并设置到请求头中data:{"username":"Q1mi","password":123456}, 
 success:function(data){console.log(data);}})
Copy after login

或者用自己写一个getCookie方法:

functiongetCookie(name){varcookieValue=null;if(document.cookie&&document.cookie!==&#39;&#39;){varcookies=document.cookie.split(&#39;;&#39;);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+&#39;=&#39;)){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}returncookieValue;}varcsrftoken=getCookie(&#39;csrftoken&#39;);
Copy after login

每一次都这么写太麻烦了,可以使用$.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);}}});
Copy after login

如果你的视图渲染的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
Copy after login

更多细节详见: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
Copy after login

或者使用

var form = document.getElementById("form1"); 
var fd = new FormData(form);
Copy after login

这样也可以直接通过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)
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles