ajax

85 阅读1分钟

一.Get (get会有缓存问题 地址栏不更改会缓存 有数据大小限制)

1.原生js

function ajax(){
  var xml=new XMLHttpRequest();

  xml.open('get', `http://`);

  var data=new FormDate(form)

  data.set('password',hex_md5(userPassword.value))

  xml.send(data);

  xml.onreadystatechange=function(){

     if(xml.readyState==4&&xml.status==200){

            console.log(JSON.parse(xml.responseText));

      }
  }
}

2.es6

> var data = new FormData(form);
>
> //(可略) data.set('password', hex_md5(password.value));
>
> fetch(`http://`,{
>
>     method:"get",
>
>     body:data,
>
> }).then(res=>res.json()).then(res=>{
>
>       console.log(res)
>
> })

二.Post (无数据大小限制 没有get快 但更安全)

post必须设置请求头

 // post方式发送的请求的参数可以在请求地址的?后面(查询字符串),也可以放到send里面

2.1.第一种请求头 (字符&) application/x-www-form-urlencoded

function ajax(){
   var xhr = new XMLHttpRequest();
>
>  xhr.open('POST', 'http://');
>
>  xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
>
>  xhr.send('a=1&b=2&name=蔡徐坤');
>
>  xhr.onreadystatechange = function() {
>
>       if (xhr.readyState == 4 && xhr.status == 200) {
>
>                 console.log(xhr.responseText);
>
>      }
>  }
>}

2.1.第二种请求头 (对象) application/json

> function ajax(){
>  var obj = {name: '李四', age: 20,sex: '男'}
>
>  var xhr = new XMLHttpRequest();
>
>  xhr.open('POST', 'http://');  
> xhr.setRequestHeader('content-type', 'application/json');
>
>      xhr.send(JSON.stringify(obj));
>
> xhr.onreadystatechange = function() {
>
>       if (xhr.readyState == 4 && xhr.status == 200) {
>
>                 console.log(xhr.responseText);
>
>      }}
>}

2.1.第三种请求头 (表单) multipart/form-data

<form id="form">

        <input type="text" name="username">

        <input type="text" name="username">

        <input type="text" name="password">

        <input type="text">

###### <!-- form里面 btn 的 type 默认是 submit -->

        <button>提交</button>

 </form>
 form.onsubmit = function() {

            // 阻止表单默认提交事件

            event.preventDefault();

            var xhr = new XMLHttpRequest();

            xhr.open('post', 'http://192.168.204.63:3004/api/add');

  


###### // 第三种数据格式  formData格式   不需要设置请求头,默认就是multipart/form-data 会自动提取form标签里面带有name属性的表单元素的键值对

            var data = new FormData(form)

            console.log(data);

            // 新增(可略)
            data.append('uuid', uuid);

            data.append('oldPsw', oldPsw.value);

            data.append('newPsw', newPsw.value);

            data.append('mobile', '17613375674');

            // 删除(可略)

            // data.delete('username');

            // 修改(可略)

            data.set('password', 'a123456.');

            // 获取(可略)

            console.log(data.get('password'), data.get('username'));

            xhr.send(data);

            xhr.onreadystatechange = function() {

                if (xhr.readyState == 4 && xhr.status == 200) {

                    console.log(xhr.responseText);

                }

            }

        }