UNPKG

asp-smart-ui-plus-test

Version:

A Component Library for Vue 3

74 lines (70 loc) 2.43 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function ajax(options = {}) { return new Promise((resolve) => { options.method = (options.method || "GET").toUpperCase(); options.dataType = options.dataType || "json"; options.async = options.async === void 0 ? true : options.async; let params = getParams(options.data || {}); let contentType; if (options.requestHeader && options.requestHeader["Content-Type"]) { contentType = options.requestHeader["Content-Type"]; } if (contentType === "application/json") { params = JSON.stringify(options.data); } else { params = getParams(options.data || {}); } let xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if (options.method === "GET") { xhr.open("GET", `${options.url}?${params}`, options.async); setRequestHeader(options, xhr); xhr.send(null); } else if (options.method === "POST") { xhr.open("POST", options.url || "", options.async); if (!options.requestHeader || options.requestHeader && !options.requestHeader["Content-Type"]) { xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" ); } setRequestHeader(options, xhr); if (!(options.data instanceof FormData)) { params = JSON.stringify({ ...options.data }); } xhr.send(params); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { const status = xhr.status; if (status >= 200 && status < 300) { resolve(JSON.parse(xhr.responseText)); options.success && options.success(JSON.parse(xhr.responseText), xhr.responseXML); } else { resolve(JSON.parse(xhr.responseText)); options.fail && options.fail(JSON.parse(xhr.responseText)); } } }; }); } function setRequestHeader(options, xhr) { if (Object.prototype.toString.call(options.requestHeader) === "[object Object]") { for (const key in options.requestHeader) { xhr.setRequestHeader(key, options.requestHeader[key]); } } } function getParams(data) { const arr = []; for (const param in data) { arr.push(`${encodeURIComponent(param)}=${encodeURIComponent(data[param])}`); } return arr.join("&"); } exports.ajax = ajax;