123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <style>
- #app {
- margin: 20px;
- }
- </style>
- <script>
- </script>
- </head>
- <body>
- <div id="app">
- 加载中……
- </div>
- <script>
- function getQueryStringByUrl(url, name) {
- let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
- let r = url.substring(url.indexOf('?') + 1).match(reg); //获取url中"?"符后的字符串并正则匹配
- let context = "";
- if (r != null)
- context = r[2];
- reg = null;
- r = null;
- return context == null || context === "" || context === "undefined" ? "" : decodeURI(context);
- }
- function getQueryString(name) {
- return getQueryStringByUrl(location.href, name);
- }
- const requestUtil = {
- xhr_send(xhr, method, headers, data) {
- if (headers) {
- for (const key in headers) {
- xhr.setRequestHeader(key, headers[key]);
- }
- }
- if (method.match(/^(POST|PUT|DELETE)$/i)) {
- if (!headers || !headers.hasOwnProperty("Content-Type")) {
- xhr.setRequestHeader("Content-Type", "application/json");
- }
- xhr.send(JSON.stringify(data));
- } else {
- xhr.send();
- }
- },
- /**
- * 异步请求:requestUtil.async('https://jsonplaceholder.typicode.com/posts/1', 'GET', null, null)
- * .then(data => console.log(data))
- * .catch(error => console.error(error));
- */
- async(url, method, data = {}, headers = {}) {
- return new Promise((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open(method, url, true);
- this.xhr_send(xhr, method, headers, data);
- xhr.onload = () => {
- resolve(JSON.parse(xhr.responseText));
- };
- xhr.onerror = () => reject(xhr.statusText);
- });
- },
- /**
- * 拼接 url
- */
- buildUrl(url, params) {
- const urlObj = new URL(url);
- // @ts-ignore
- for (const key in params) {
- urlObj.searchParams.set(key, params[key]);
- }
- return urlObj.toString();
- },
- /**
- * 同步请求 let a = request.sync("https://httpbin.tianyunperfect.cn/ip","GET",null,null)
- */
- sync(url, method, data = {}, headers = {}) {
- const xhr = new XMLHttpRequest();
- xhr.open(method, url, false);
- this.xhr_send(xhr, method, headers, data);
- return JSON.parse(xhr.responseText);
- },
- };
- let id = getQueryString("id");
- console.log(id)
- // 如果没有id参数,直接返回
- if (id) {
- requestUtil.async("https://app.yizhigj.com/api/content/getById?id=" + id, "GET",).then(res => {
- document.getElementById("app").innerHTML = res.data.content;
- });
- }
- </script>
- </body>
- </html>
|