有勇气的牛排博客

前端异步请求 ajax与axios

有勇气的牛排 1177 前端 2021-11-24 23:48:28

1 ajax

有关token传递有两种方法,一种使用beforeSend,另一种使用headers(二选一即可)。

$.ajax({ url: '/wallet', type: 'POST', dataType: 'json', beforeSend: function (request) { // request.setRequestHeader("Authorization", "token"); }, headers: { 'Authorization': "token" }, data: { 'money': money }, success:function (res) { }, error:function () { } });

2 axios

官网:https://www.axios-http.cn/

2.1 安装

npm

npm install axios

bower

bower install axios

yarn

yarn add axios

jsDelivr CDN

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

unpkg CDN

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

3 常用轮子

3.1 函数

$(function () { });
$("#submit").click(function () { var money = $("#money").val() alert(money) });

3.2 遍历数组

var str = ''; for (i = 0; i < res.results.length; i++) { str += "<tr>" + " <td>" + res.results[i].uid + "</td>\n" + " <td><a href='/kfDetail'></a></td>\n" + " </tr>" $("#content").html(str); }

3.3 重定向

location.href = '/shoplist/'+content

留言

专栏
文章
加入群聊