2

Ajax请求的使用

 3 years ago
source link: https://blog.csdn.net/qq_39794062/article/details/115803834
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、什么是 AJAX 请求

  • AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
  • AJAX是一种浏览器通过 js 异步发起请求,实现局部更新页面。Ajax 请求的局部更新,浏览器地址栏不会发生变化,局部更新不会舍弃原来页面的内容。

二、原生 AJAX 请求的示例

		<script type="text/javascript">
			//这个按钮绑定的函数,使用js发起Ajax请求,访问服务器AjaxServlet中JavaScriptAjax
			function ajaxRequest() {
// 				1、我们首先要创建XMLHttpRequest
				var xmlHttpRequest = new XMLHttpRequest();

// 				2、调用open方法设置请求参数
				xmlHttpRequest.open("GET","http://localhost:8080/json_Ajax_i18n/ajaxServlet?action=javaScriptAjax",true);

// 				3、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
				xmlHttpRequest.onreadystatechange = function () {
					if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){

					    var jsonObj = JSON.parse(xmlHttpRequest.responseText);
					    //把响应的数据显示在页面上
					    document.getElementById("div01").innerText = "编号:" + jsonObj.id + ",姓名:" + jsonObj.name ;

					}
                }

// 				4、调用send方法发送请求
                xmlHttpRequest.send();
			}
		</script>

三、jQuery 中的 AJAX 请求

在这里插入图片描述

				// ajax请求
				$("#ajaxBtn").click(function(){
					
					$.ajax({
						url:"http://localhost:8080/json_Ajax_i18n/ajaxServlet",
						data:"action=jQueryAjax",
						type:"GET",
						success:function (data) {
						    
							alert("服务器返回的数据是:" + data);

                        },
						dataType:"text"
					})

				});

在这里插入图片描述

				// ajax--get请求
				$("#getBtn").click(function(){

					$.get("http://localhost:8080/json_Ajax_i18n/ajaxServlet","action=jQueryGet",function (data) {

                        alert("服务器返回的数据是:" + data);

                    },"json");
					
				});
				
				// ajax--post请求
				$("#postBtn").click(function(){
					// post请求
                    $.post("http://localhost:8080/json_Ajax_i18n/ajaxServlet","action=jQueryPost",function (data) {

                        alert("服务器返回的数据是:" + data);

                    },"json");
					
				});

在这里插入图片描述

				// ajax--getJson请求
				$("#getJSONBtn").click(function(){
					// 调用
                    $.getJSON("http://localhost:8080/json_Ajax_i18n/ajaxServlet","action=jQueryPost",function (data) {

                        alert("服务器返回的数据是:" + data);

                    });

				});

表单序列化 serialize()可以把表单中所有表单项的内容都获取到,并以 name=value&name=value 的形式进行拼接。

				// ajax请求
				$("#submit").click(function(){
					// 把参数序列化
					//$("#form01").serialize();

                    $.getJSON("http://localhost:8080/json_Ajax_i18n/ajaxServlet","action=jQuerySerialize&" + $("#form01").serialize(),function (data) {
						
                    });

				});

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK