$axios.post 表单序列化 URLSearchParams

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33603809/article/details/90521698

URLSearchParams的用法

这个方法可以将get/post要传的参数序列化,再通过this.$axios.post(‘api/address’, params)发送请求。
具体的用法如下:

// POST
const params = new URLSearchParams();
params.append('name', this.name);
params.append('password', this.password);
this.$axios.post('api/address', params).then(result => {
	// success
}, error => {
	// fail
}).catch(error => {});

// GET
const params = new URLSearchParams(str);
this.$axios.get('api/address', params).then(result => {
	// success
}, error => {
	// fail
}).catch(error => {});

这里是正常显示,当然URLSearchParams是有兼容行的,具体可以查看这个网站: https://caniuse.com/

看到get方法可以将参数放在new里,于是我也这么写:

	// POST
	const params = new URLSearchParams({name: this.name, password, this.password});
	this.$axios.post('api/address', params).then(result => {
		// success
	}, error => {
		// fail
	}).catch(error => {});

发现低版本的浏览器发送的是空的params,兼容行不好。

最后,奉上封装好的序列化方法,因为URLSearchParams有兼容性,所以就暂时不被考虑了,手写(大牛的)一个比较靠谱。

function getType(obj) {
    return Object.prototype.toString
        .call(obj)
        .replace(/^\[\w+ (\w+)\]$/, '$1')
        .toLowerCase();
}
// scope暂时用不上,后面优化
function convert(params, obj, scope) {
    let type;
    let array = Array.isArray(obj);
    let hash = getType(obj) === 'object';

   Object.keys(obj).forEach(function(key) {
        let value = obj[key];
        type = getType(value);
        if (scope) { key =
            scope +
            '[' +
            (hash || type === 'object' || type === 'array' ? key : '') +
            ']'; }
        // handle data in serializeArray() format
        if (!scope && array) { params.add(value.name, value.value) }
        // recurse into nested objects
        else if (type === 'array' || type === 'object') { serialize(params, value, key) }
        else { params.add(key, value) }
    });
}
export function serialize(obj) {
    let params = [];
    params.add = function(key, value) {
        if (value == null) value = '';
        this.push(escape(key) + '=' + escape(value));
    };
    convert(params, obj);
    return params.join('&').replace(/%20/g, '+');
};

要优化点:1、可以序列化merge 2、scope参数

猜你喜欢

转载自blog.csdn.net/qq_33603809/article/details/90521698
今日推荐