基本业务描述
构建一个名为Ajax-01的html页面。首先,在文本框中注册焦点事件,基于焦点事件判断内容是否存在,其次点击save按钮时将用户内容异步提交到服务器端。
客户端代码实现
Insert title hereThe Ajax Page
Ajax 表单请求
type="button" οnclick="doSave()" value="save">
function doSave(){
//基于dom事件的Ajax请求
//1.基于dom事件创建XHR对象
var xhr=new XMLHttpRequest();
//2.注册XHR对象状态监听,通过回调函数(rollback)处理状态信息。
//onreadystatechange存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
//xhr.responseText获取响应数据
document.getElementById("result").innerHTML=""+xhr.responseText+"";
}
};
//3.创建与服务端的连接
//var name=document.getElementById("nameId").value;
var name=document.forms[0].name.value;
xhr.open("POST","/doSave",true);
//使用post请求要设置请求头(规定)
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.发送异步请求实现与服务端的通讯
xhr.send("name="+name);//Post请求send方法传值
}
服务端代码实现
服务端中添加代码以处理客户端请求。package com.cy.ajaxcontroller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//这是一个服务端,用来处理客户端的请求
@Controller
@RequestMapping("/")
public class AjaxController {
//假如这是存储数据的表
private List names=new ArrayList();
@RequestMapping("doSave")
@ResponseBody
//将客户端请求的数据name写入到names对应的集合
public String doSave(String name) {
System.out.println("name="+name);
names.add(name);
return "save ok";
}
}