欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js api 之 fetch、querySelector、form、atob及btoa

程序员文章站 2023-08-12 11:04:38
js api 之 fetch、querySelector、form、atob及btoa 转载请注明出处: "https://www.cnblogs.com/funnyzpc/p/11095862.html" js api即为JavaScript内置函数,本章就说说几个比较实用的内置函数,内容大致如下 ......

js api 之 fetch、queryselector、form、atob及btoa

转载请注明出处:

js api即为javascript内置函数,本章就说说几个比较实用的内置函数,内容大致如下:

  • fecth http请求函数
  • queryselector 选择器
  • form 表单函数
  • atob与btoa base64函数

base64之atob与btoa

以前,在前端,我们是引入base64.js后调用api实现数据的base64的编码和解码的运算,现在新的es标准为我们提供了base64
的支持,主要用法如下:

  • 编码:window.btoa(param);
   输入> window.btoa("hello");
   输出> "agvsbg8="
  • 解码:window.atob(param)
   输入:window.atob("agvsbg8=");
   输出:"hello"

dom选择器之 queryselector

dom选择器在jquery中用的十分广泛,极大地方便了前端开发,现在你有了__queryselector__,不用引入恼人的js及
各种js依赖,一样便捷开发~

  • id选择
    // 获取dom中的内容
    document.queryselector("#title").innertext;
    // 将dom设置为粉红色背景
    document.queryselector("#title").style.backgroundcolor="pink";
    // 获取dom的class属性
    document.queryselector("#title").getattribute("class");
    // 移除dom
    document.queryselector("#title").remove();
    // 获取子dom
    document.queryselector("#title").childnodes;
    // 给dom添加click事件(点击后弹出 "success")
    document.queryselector("#title").onclick = function(){alert("success")};
    // 给dom添加属性(添加一个可以为name,value为hello的属性)
    document.queryselector("#title").setattribute("name","hello");
  • class选择
    // 获取dom中的内容
    document.queryselector(".title").innertext;
    // 将dom设置为粉红色背景
    document.queryselector(".title").style.backgroundcolor="pink";
    // 获取dom的class属性
    document.queryselector(".title").getattribute("class");
    // 移除dom
    document.queryselector(".title").remove();
    // 获取子dom
    document.queryselector(".title").childnodes;
    // 给dom添加click事件(点击后弹出 "success")
    document.queryselector(".title").onclick = function(){alert("success")};
  • tag选择器(dom名称)
    // 获取dom中的内容
    document.queryselector("h4").innertext;
    // 将dom设置为粉红色背景
    document.queryselector("h4").style.backgroundcolor="pink";
    // 获取dom的class属性
    document.queryselector("h4").getattribute("class");
    // 移除dom
    document.queryselector("h4").remove();
    // 获取子dom
    document.queryselector("h4").childnodes;
    // 给dom添加click事件(点击后弹出 "success")
    document.queryselector("h4").onclick = function(){alert("success")};
    // 给dom添加属性(添加一个可以为name,value为hello的属性)
    document.queryselector("h4").setattribute("name","hello");
  • 自定義屬性選擇(多用於表單)
    // 获取dom的value值
    document.queryselector("input[name=age]").value;
    // 将dom设置为粉红色背景
    document.queryselector("input[name=age]").style.backgroundcolor="pink";
    // 获取dom的class属性
    document.queryselector("input[name=age]").getattribute("class");
    // 移除dom
    document.queryselector("input[name=age]").remove();
    // 获取子dom
    document.queryselector("input[name=age]").childnodes;
    // 给dom添加click事件(点击后弹出 "success")
    document.queryselector("input[name=age]").onclick = function(){alert("success")};
    // 给dom添加属性(添加一个可以为name,value为hello的属性)
    document.queryselector("input[name=age]").setattribute("name","hello");

form表單函數

以前我們是沒有表單函數的時候,如果做表單的提交大多定義一個提交按鈕,用jquery+click函數實現表單提交,
或者獲取參數後使用ajax提交,對於後者暫且不說,對於前者 es標準提供了新的函數 form函數,當然這個只是
document的一個屬性而已,需要提醒的是這個函數使用的前提是需要給form標籤定義一個name属性,这个name属性
的值即为表单函数的函数名字(也可为属性),具体用法如下;

比如我们的表单是这样的:

   // html表单
   <form name="fm" method="post" action="/submit">
       <input type="text" name="age" placeholder="请输入年龄"/>
   </form>

这个时候我们可以这样操作表单:

    // 提交表单
    document.fm.submit();
    // 获取表单的name属性值
    document.fm.name;
    // 获取表单的dom
    document.fm.elements;
    // resetb表单
    document.fm.reset();
    // ...更多操作请在chrome控制台输入命令

fetch

fetch 为js 新内置的http请求函数,用于替代ajax及原始的xmlhttprequest,与ajax相似的是它提供了请求头,异步或同步方法,同时也提供了get、put、delete、option等
请求方式,唯一缺憾的是除了post(json)方式提交外,其他方式均需要自行组装参数,这里仅给出几个简单样例供各位参考。

fetch:get请求

html:

    <form method="get" style="margin-left:5%;">
        <label>name:</label><input type="text" name="name"/>
        <label>price:</label><input type="number" name="price"/>
        <label><button type="button" onclick="getaction()">get提交</button></label>
    </form>

javascript:

    function getaction() {
            // 组装请求参数
            var name = document.queryselector("input[name=name]").value;
            var price = document.queryselector("input[name=price]").value;

            fetch("/get?name="+name+"&price="+price, {
                method: 'get',
                headers: {
                    'content-type': 'application/json'
                },
                // body: json.stringify({"name":name,"price":price})
            })
            .then(response => response.json())
            .then(data =>
                document.getelementbyid("result").innertext = json.stringify(data))
            .catch(error =>
                console.log('error is:', error)
            );
        }

这里的get请求(如上),注意如下:

  • 需手动拼接参数值/get?name=name&price=price
  • 由于get请求本身是没有请求体的,所以fetch的请求配置中一定不能有body的配置项
  • 由于get请求本身是没有请求体的,所以headers项可以不配置
  • 请求结果在第一个then的时候,数据是一个steam,所以需要转换成json(调用json()方法)
  • 请求结果在第二个then的时候仍然是一个箭头函数,这个时候如需要对数据进行处理请调用自定义函数处理
fetch:post(json)请求

html:

    <form method="get" style="margin-left:5%;">
        <label>name:</label><input type="text" name="name"/>
        <label>price:</label><input type="number" name="price"/>
        <label><button type="button" onclick="getaction()">get提交</button></label>
    </form>

javascript:

    function getaction() {
            // 组装请求参数
            var name = document.queryselector("input[name=name]").value;
            var price = document.queryselector("input[name=price]").value;
            price = number(price)
            fetch("/post", {
                method: 'post',
                headers: {
                    'content-type': 'application/json'
                },
                body: json.stringify({"name":name,"price":price})
            })
            .then(response => response.json())
            .then(data =>
                document.getelementbyid("result").innertext = json.stringify(data))
            .catch(error =>
                console.log('error is:', error)
            );
       }

这里需要注意对是:

  • post请求的请求头的内容类型必须是application/json,至于application/x-www-form-urlencoded我一直没测通过,请各位指点
  • 请求体中的数据对象必须使用json.stringify() 函数转换成字符串
fetch:post(form)请求

html:

       <form method="get" style="margin-left:5%;" name="fm" action="/form">
            <label>name:</label><input type="text" name="name"/>
            <label>price:</label><input type="number" name="price"/>
        </form>

javascript:

        function getaction() {
            // 组装请求参数
            let name = document.queryselector("input[name=name]").value;
            let price = document.queryselector("input[name=price]").value;
            // price = number(price)
            /*
            let formdata = new formdata();
            formdata.append("name",name);
            formdata.append("price",price);
            */
            let data = new urlsearchparams();
            data.set("name",name);
            data.set("price",price);
            fetch("/form", {
                method: 'post',
                headers: {
                     "content-type":"application/x-www-form-urlencoded;charset=utf-8"
                },
                body: data
            })
            .then( response =>response.json() )
            .then(function (data){
                this.success(data);
            })
            .catch(error =>
                console.log('error is:', error)
            );
        }
        function success(data) {
            document.getelementbyid("result").innertext = json.stringify(data)
            alert(window.atob(data.sign))
        }

可以看到中间改过几次,实在不理想,后有改成urlsearchparams来拼装请求数据,后来成功了,各位要有其他方式请指点一二。