学习Ajax的体会

Ajax技术实战
输入区号触发Ajax异步请求,从服务器获取区号所对应的省市信息,并在jsp页面中进行更新填充


这种是post方式需要在open();后设置请求头setRequestHeader();数据放在send();中
使用get方式不用设置请求头;数据放在url中这种形式:var url=“AjaxServlet?+zipCode=” + zipCode;

jQuery Ajax实现方式:

function doAjax(obj){
            var zipCode=obj.value;
            $.ajax({
                type:'post',
                url:'AjaxServlet',
                data:"zipCode="+zipCode,
                success: function (data) {
                    console.log(data)
                    var responseData = data.split(",")
                    //jQuery方法
                    $("#province").val(responseData[0]);
                    //dom方法
                    document.getElementById("city").value = responseData[1];
                }
            })
        }

html:


区号:

省份:

市区:

@WebServlet("/AjaxServlet")
public class AjaxServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        Map<String, String> datas = new HashMap<>();
        datas.put("0532", "山东,青岛");
        datas.put("0351", "山西,太原");
        datas.put("0531", "山东,济南");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String zipCode = request.getParameter("zipCode");
        String data = datas.get(zipCode);
        if (data == null) {
            data = "error,error";
        }
        response.getWriter().print(data);

    }
}

你可能感兴趣的:(学习Ajax的体会)