zoukankan      html  css  js  c++  java
  • ajax实例二:发送post请求

    第二例:发送POST请求(如果发送请求时需要带有参数,一般都用POST请求)

    * open:xmlHttp.open("POST" ....);
    * 添加一步:设置Content-Type请求头:
    > xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    * send:xmlHttp.send("username=zhangSan&password=123");//发送请求时指定请求体

    -------------------------------------------------------------------------------------------

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>My JSP 'ajax1.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
    //创建异步对象
    function createXMLHttpRequest() {
    try {
    return new XMLHttpRequest();//大多数浏览器
    } catch (e) {
    try {
    return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
    } catch (e) {
    try {
    return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本
    } catch (e) {
    alert("哥们儿,您用的是什么浏览器啊?");
    throw e;
    }
    }
    }
    }

    window.onload = function() {//文档加载完毕后执行
    var btn = document.getElementById("btn");
    btn.onclick = function() {//给按钮的点击事件注册监听
    /*
    ajax四步操作,得到服务器的响应
    把响应结果显示到h1元素中
    */
    /*
    1. 得到异步对象
    */
    var xmlHttp = createXMLHttpRequest();
    /*
    2. 打开与服务器的连接
    * 指定请求方式
    * 指定请求的URL
    * 指定是否为异步请求
    */
    xmlHttp.open("POST", "<c:url value='/AServlet'/>", true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    /*
    3. 发送请求
    */
    xmlHttp.send("username=222&password=234");//GET请求没有请求体,但也要给出null,不然FireFox可能会不能发送!
    /*
    4. 给异步对象的onreadystatechange事件注册监听器
    */
    xmlHttp.onreadystatechange = function() {//当xmlHttp的状态发生变化时执行
    // 双重判断:xmlHttp的状态为4(服务器响应结束),以及服务器响应的状态码为200(响应成功)
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
    // 获取服务器的响应结束
    var text = xmlHttp.responseText;
    // 获取h1元素
    var h1 = document.getElementById("h1");
    h1.innerHTML = text;
    }
    };
    };
    };
    </script>
    </head>

    <body>
    <button id="btn">点击这里</button>
    <h1 id="h1"></h1>
    </body>
    </html>

  • 相关阅读:
    Sql语句中IN和exists的区别及应用
    时间戳/Date(1354116249000)/ 转换
    SqlServer不允许更改字段类型(表中已有数据)
    Firefox内存占用过高解决方法
    接口开发中的测试问题
    c# winform 窗体起始位置 设置
    【整理】C#文件操作大全(SamWang)
    C#实现JSON序列化与反序列化
    解决方案资源管理器中跟踪活动项
    C#中方法的参数的四种类型
  • 原文地址:https://www.cnblogs.com/danyuzhu11/p/6837136.html
Copyright © 2011-2022 走看看