AJAX学习笔记(三)_XMLHttpRequest向服务器发送请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38242407/article/details/78104540

向服务器发送请求

向服务器发送请求需要调用XMLHttpRequest 对象的 open() 和 send() 方法。

open(method,url,async)

规定请求的类型、URL 以及是否异步处理请求。
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)

method

Get or Post

GET 更简单也更快,并且在大部分情况下都能用。

但在以下情况中,使用 POST 请求:
无法使用缓存文件(更新服务器上的文件或数据库)
向服务器发送大量数据(POST 没有数据量限制)
发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

/**
 * 通过post方式提交
 * */
function postSend(){
    var value = document.getElementById("content").value;
    alert(value);
    //初始化XMLHttpRequest对象
    createXMLHttpRequest();
    //创建请求的URL
    var url = "ajaxServlet"
    //打开与服务器的连接,使用post方式
    xhr.open("POST", url, true);
    //post方式需要设置请求消息头
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //设置处理响应的回调函数
    xhr.onreadystatechange = processResponse;
    //发送请求并设置参数,参数的设置为param=value的形式
    xhr.send("value="+value);
}
/**
 * 通过GET请求
 * */
function getSend(){
    var value = document.getElementById("content").value;
    //alert(value);
    //初始化XMLHttpRequest对象
    createXMLHttpRequest();
    alert("创建成功");
    //创建请求的URL,get方式采用url拼接参数
    var url = "ajaxServlet?value="+value;
    xhr.open("GET", url, true);
    //设置处理响应的回调函数
    xhr.onreadystatechange = processResponse;
    xhr.send(null);
}
/**
 * 设定的回调函数
 * */
function processResponse(){
    //响应完成且响应正常
    if(xhr.readyState == 1){
        alert("XMLHttpRequest对象开始发送请求");
    }else if(xhr.readyState == 2){
        alert("XMLHttpRequest对象的请求发送完成");
    }else if(xhr.readyState == 3){
        alert("XMLHttpRequest对象开始读取服务器的响应");
    }else if(xhr.readyState == 4){
        alert("XMLHttpRequest对象读取服务器响应结束");
        if(xhr.status == 200){
            //信息已经成功返回,开始处理信息
            //先捕获下所有的请求头
            var headers = xhr.getAllResponseHeaders();
            alert("所有的请求头= "+headers);
            //得到服务器返回的信息
            var infor = xhr.responseText;
            alert("服务器端的响应 = "+infor);
        }else{
            alert("所请求的服务器端出了问题");
        }
    }
}

注:在使用Get请求时,为了保证不是缓存的内容,可以加一个唯一的标识,可后缀上date()或Math.random()。
注:在post方式提交的时候,post提交请求前需要先设置请求头,用setRequestHeader(“label”,”value”)。

url

url是服务器上文件的地址。

async

要想使用xhr对象的话,async必须是true。

send(string)

将请求发送到服务器。
string:仅用于 POST 请求

如果是Get请求,send()方法一般不带参数或null,即使你加了参数也会被转为null。

如果是POST请求,xhr.send(data)的参数data可以是以下几种类型:

  • ArrayBuffer
  • Blob
  • Document
  • DOMString
  • FormData

data参数的数据类型会影响请求头部content-type的默认值:

  1. 如果data是 Document 类型,同时也是HTML
    Document类型,则content-type默认值为text/html;charset=UTF-8;否则为application/xml;charset=UTF-8;

  2. 如果data是 DOMString 类型,content-type默认值为text/plain;charset=UTF-8;

  3. 如果data是 FormData 类型,content-type默认值为multipart/form-data;

  4. 如果data是其他类型,则不会设置content-type的默认值。

  5. 如果用xhr.setRequestHeader()手动设置了中content-type的值,以上默认值就会被覆盖。


猜你喜欢

转载自blog.csdn.net/qq_38242407/article/details/78104540
今日推荐