H5页面可以引用的一些JS常用小方法

写了一些单个的小页面可以引入的常用js方法,省了自己手写的时间,需要时可以保存为js文件然后直接引用。

const jsToolsH5 = {
    
    
	/**
	 * 获取url的查询参数
	 * @param {string} param - 需要获取的参数名称
	 * @returns {string} - 返回值是一个字符串
	 */
	getUrlParam: (param) => {
    
    
		if (!param || typeof param !== 'string') {
    
    
			return ''
		} else {
    
    
			try {
    
    
				const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)', 'i')
				const character = decodeURIComponent(window.location.search.substring(1)).match(reg)
				if (!!character && character.length > 0 && !!character[2] && character[2] != 'null') {
    
    
					// 把语言参数langId后边的2位国家代码变成大写字母
					if (param === 'langId') {
    
    
						const _langAry = character[2].split('_')
						_langAry[1] = _langAry[1].toUpperCase()
						character[2] = _langAry.join('_')
					}
					return character[2]
				} else {
    
    
					return ''
				}
			} catch (error) {
    
    
				throw new Error('URL Param Error')
			}
		}
	},

	/**
	 * 把一个对象拼接成字符串
	 * @param {object} paramsObject - 需要拼接在url后边的对象
	 * @returns {string} - 返回值是一个字符串
	 */
	convertObjectToString: (paramsObject) => {
    
    
		if (!!paramsObject && paramsObject.constructor === Object && Object.keys(paramsObject).length > 0) {
    
    
			let _str = ''
			_str = Object.keys(paramsObject).reduce((prev, current, currentIndex, array) => {
    
    
				if (currentIndex === array.length - 1) {
    
    
					return prev + current + '=' + paramsObject[current]
				} else {
    
    
					return prev + current + '=' + paramsObject[current] + '&'
				}
			}, '')
			return _str
		} else {
    
    
			throw new Error('Not a Object Type')
		}
    },
    
	/**
	 * 原生JS发送http请求
	 * @param {object} params - 传入的对象
	 * @param {string} params.url - 传入对象的 url 属性,可以直接把查询参数拼接在url后边
	 * @param {string} [params.type = 'GET'] - 传入对象的 type 属性
	 * @param {*} [params.data] - 传入对象的 data 属性可以是json对象或Qs序列化之后的查询字符串等
	 * @param {string} [params.contentType] - 传入对象的 contentType 属性: application/json 或者 application/x-www-form-urlencoded
	 * @returns {promise} - 返回值是一个promise对象,需要用.then接收
	 */
	ajaxPromise: (params) => {
    
    
		return new Promise((resolve, reject) => {
    
    
			const _contentType = params.contentType || 'application/json'
			const _data = params.data ? params.data : null
			if (_contentType === 'application/x-www-form-urlencoded' && !!_data) {
    
    
				let _reg = /^\S+=\S+/g
				if (!_reg.test(params.data)) {
    
    
					throw new Error('请先使用Qs序列化Data')
				}
			}
			const xhr = new XMLHttpRequest()
			xhr.open(params.type || 'POST', params.url)
			xhr.setRequestHeader('Content-type', _contentType)
			xhr.send(_data)
			xhr.onload = () => {
    
    
				if (xhr.status === 200) {
    
    
					resolve(JSON.parse(xhr.responseText))
				} else {
    
    
					reject(Error(xhr.statusText))
				}
			}
		})
	},
}

猜你喜欢

转载自blog.csdn.net/xjtarzan/article/details/131088881