Home > Web Front-end > JS Tutorial > How to use ajax? Ajax use case analysis

How to use ajax? Ajax use case analysis

寻∝梦
Release: 2018-09-10 13:52:51
Original
1043 people have browsed it

This article mainly introduces the usage details of ajax, as well as the use case analysis of ajax. Let’s take a look at this article now

$.ajax() method usage case

You need to introduce jquery files. This case uses jquery-2.0.0.js

1, ajax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-2.0.0.js"></script>
<script type="text/javascript">
	$(function() {
		$("#submit").click(function() {
			$.ajax({
				url : "ajax.do",//请求的url
				type : "post",//请求方式
				data : {//传递的数据
					name : $("#name").val()
				},
				dataType : "text",//后台数据返回类型
				success : function(data) {//响应成功执行的方法
					alert(data);
				},
				error : function() {//出现异常执行方法
					alert("出现异常啦...");
				}

			});
		});
	});
</script>
</head>
<body>
	<form action="">
		用户名:<input type="text" name="name" id="name" /><br /> 
		<input type="button" id="submit" value="提交" />
	</form>
</body>
</html>
Copy after login

2. UserServlet.java

@WebServlet("/ajax.do")
public class AjaxServlet extends HttpServlet {	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 请求中文乱码处理
		request.setCharacterEncoding("UTF-8");
		// 响应中文乱码处理
		response.setHeader("Content-Type", "text/html;charset=utf-8");
		// 接收数据
		String name = request.getParameter("name");
		System.out.println(name);
		// 测试出现异常,ajax会执行error
		// throw new IOException();
		PrintWriter out = response.getWriter();
		// 响应的信息
		out.write("成功啦...");
		out.flush();
		out.close();
	}
}
Copy after login

##$.ajax() method is introduced in detail as follows (from w3school)

jQuery ajax - ajax() method

Instance

Passed AJAX loads a piece of text:

jQuery code:

$(document).ready(function(){
  $("#b01").click(function(){
  htmlobj=$.ajax({url:"/jquery/test1.txt",async:false});
  $("#myp").html(htmlobj.responseText);
  });
});
Copy after login
HTML code:

<p id="myp"><h2>Let AJAX change this text</h2></p>
<button id="b01" type="button">Change Content</button>
Copy after login

Definition and usage

ajax() method loads remote data through HTTP requests.

This method is the underlying AJAX implementation of jQuery. For simple and easy-to-use high-level implementations, see $.get, $.post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you won't need to manipulate this function directly unless you need to manipulate less commonly used options for more flexibility.

In the simplest case, $.ajax() can be used directly without any parameters.

Note: All options can be set globally through the $.ajaxSetup() function.

Syntax

jQuery.ajax([settings])
Copy after login

ParametersDescription

参数

  • options

  • 类型:Object

    可选。AJAX 请求设置。所有选项都是可选的。

  • async

  • 类型:Boolean

    默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。

    注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。

  • beforeSend(XHR)

  • 类型:Function

    发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。

    XMLHttpRequest 对象是唯一的参数。

    这是一个 Ajax 事件。如果返回 false 可以取消本次 ajax 请求。

  • cache

  • 类型:Boolean

    默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面。

    jQuery 1.2 新功能。

  • complete(XHR, TS)

  • 类型:Function

    请求完成后回调函数 (请求成功或失败之后均调用)。

    参数: XMLHttpRequest 对象和一个描述请求类型的字符串。

    这是一个 Ajax 事件。

  • contentType

  • 类型:String

    默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。

    默认值适合大多数情况。如果你明确地传递了一个 content-type 给 $.ajax() 那么它必定会发送给服务器(即使没有数据要发送)。

  • context

  • 类型:Object

    这个对象用于设置 Ajax 相关回调函数的上下文。也就是说,让回调函数内 this 指向这个对象(如果不设定这个参数,那么 this 就指向调用本次 AJAX 请求时传递的 options 参数)。比如指定一个 DOM 元素作为 context 参数,这样就设置了 success 回调函数的上下文为这个 DOM 元素。

    就像这样:

    $.ajax({ url: "test.html", context: document.body, success: function(){
            $(this).addClass("done");
          }});
    Copy after login
  • data

  • 类型:String

    发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

  • dataFilter

  • 类型:Function

    给 Ajax 返回的原始数据的进行预处理的函数。提供 data 和 type 两个参数:data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。

  • dataType

  • 类型:String

    预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:

    • "xml": 返回 XML 文档,可用 jQuery 处理。

    • "html": 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。

    • "script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)

    • "json": 返回 JSON 数据 。

    • "jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

    • "text": 返回纯文本字符串

  • error

  • 类型:Function

    默认值: 自动判断 (xml 或 html)。请求失败时调用此函数。

    有以下三个参数:XMLHttpRequest 对象、错误信息、(可选)捕获的异常对象。

    如果发生了错误,错误信息(第二个参数)除了得到 null 之外,还可能是 "timeout", "error", "notmodified" 和 "parsererror"。

    这是一个 Ajax 事件。

  • global

  • 类型:Boolean

    是否触发全局 AJAX 事件。默认值: true。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 可用于控制不同的 Ajax 事件。

  • ifModified

  • 类型:Boolean

    Only get new data when the server data changes. Default value: false. Use HTTP packet Last-Modified header information to determine. As of jQuery 1.4, it also checks the server-specified 'etag' to make sure the data has not been modified.

  • jsonp

  • Type: String

    Override the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in a GET or POST request such as {jsonp:'onJsonPLoad'} which will cause "onJsonPLoad=?" to be passed to the server.

  • jsonpCallback

  • Type: String

    Specify a callback function name for the jsonp request. This value will be used instead of the random function name automatically generated by jQuery. This is mainly used to allow jQuery to generate unique function names so that it is easier to manage requests and provide callback functions and error handling. You can also specify this callback function name when you want the browser to cache GET requests.

  • password

  • Type: String

    Password used to respond to HTTP access authentication requests

  • processData

  • Type: Boolean

    Default value: true. By default, the data passed in through the data option, if it is an object (technically speaking, as long as it is not a string), will be processed and converted into a query string to match the default content type "application/x-www-form-urlencoded" ". Set to false if you want to send DOM tree information or other information that you don't want to convert.

  • scriptCharset

  • Type: String

    Only when the dataType is "jsonp" or "script" when requested, and type Only "GET" will be used to force modification of charset. Usually only used when the local and remote content encodings are different.

  • success

  • Type: Function

    The callback function after the request is successful.

    Parameters: Data returned by the server and processed according to the dataType parameter; a string describing the status.

    This is an Ajax event.

  • traditional

  • Type: Boolean

    If you want to serialize data in the traditional way, then set is true. Please refer to the jQuery.param method under the Tools category.

  • timeout

  • Type: Number

    Set the request timeout (milliseconds). This setting overrides the global setting.

  • type

  • Type: String

    Default value: "GET"). Request method ("POST" or "GET"), default is "GET". Note: Other HTTP request methods such as PUT and DELETE can also be used, but are only supported by some browsers.

  • url

  • Type: String

    Default value: Current page address. The address to send the request to.

  • username

  • Type: String

    Username used to respond to HTTP access authentication requests.

  • xhr

  • Type: Function

    Needs to return an XMLHttpRequest object. The default is ActiveXObject under IE and XMLHttpRequest otherwise. Used to override or provide an enhanced XMLHttpRequest object. This parameter was not available before jQuery 1.3.

Callback function

If you want to process the data obtained by $.ajax(), you need to use the callback function: beforeSend, error, dataFilter, success, complete.

beforeSend

Call before sending the request, and pass in an XMLHttpRequest as a parameter.

error

Called when a request error occurs. Passing in the XMLHttpRequest object, a string describing the error type, and an exception object (if any)

dataFilter

Called after the request is successful. Pass in the returned data and the value of the "dataType" parameter. And must return new data (possibly processed) passed to the success callback function.

success

Called after request. Pass in the returned data and a string containing the success code.

complete

This function is called when the request is completed, regardless of success or failure. Pass in the XMLHttpRequest object, and a string containing a success or error code.

Data type

$.ajax() function relies on information provided by the server to process the returned data. If the server reports that the returned data is XML, the returned results can be iterated over using normal XML methods or jQuery selectors. If other types are seen, such as HTML, the data is treated as text.

You can also specify other different data processing methods through the dataType option. In addition to simple XML, you can also specify html, json, jsonp, script or text.

Among them, the data returned by text and xml types will not be processed. The data simply passes the responseText or responseHTML attribute of the XMLHttpRequest to the success callback function.

Note: We must ensure that the MIME type reported by the web server matches the dataType we select. For example, in the case of XML, the server must declare text/xml or application/xml to obtain consistent results.

If specified as html type, any embedded JavaScript will be executed before the HTML is returned as a string. Similarly, if the script type is specified, the server-side generated JavaScript will be executed first, and then the script will be returned as text data.

If specified as json type, the obtained data will be parsed as a JavaScript object, and the constructed object will be returned as the result. To achieve this, it first attempts to use JSON.parse(). If the browser does not support it, a function is used to build it.

JSON data is a kind of structured data that can be easily parsed through JavaScript. If the obtained data file is stored on a remote server (with different domain names, that is, cross-domain data acquisition), you need to use the jsonp type. Using this type creates a query string parameter callback=? which is appended to the requested URL. The server should add the callback function name before the JSON data in order to complete a valid JSONP request. If you want to specify the parameter name of the callback function instead of the default callback, you can set the jsonp parameter of $.ajax(). (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)

Note: JSONP is an extension of the JSON format. It requires some server-side code to detect and handle query string parameters.

If the script or jsonp type is specified, then when data is received from the server, the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
settings Optional. A collection of key-value pairs used to configure Ajax requests.

You can set the default value of any option through $.ajaxSetup().