Ajax请求,值为空的字段不传递到后端

2,366 阅读1分钟

参数为对象时,只传递非空属性至后端

  • 发起Ajax请求时,参数可能是对象类型,并且对象包含多个字段。此时,如果后端要求只传递该对象下有值的字段,那么以下方式可生效。
// 这里的alipayAccount等属性如果值不为空会被传递到后端,否则不会被传递
async submit(){
    if (!this.hasOne) return

    let url = this.$ajaxUrl.rightCenter.space_changeWithdrawalSetting;
    let params = {
        alipayAccount: this.input_alipay_account || undefined,
        cardNo: this.input_bank_account || undefined,
        idCard: this.input_idcard || undefined,
        name: this.input_name || undefined,
    };

    let res = await this.https.post(url, params);

    // 填写有问题,给予警告
    if (res.code === '0001'){
        return this.$Message.warning(res.msg);
    }

    if (res.code !== '0000'){
        return this.$Message.error(res.msg);
    }

    this.$Message.success('修改成功');
    this.$emit('success');
    this.getPayeeInformation();

},
  • 假设alipayAccount为空,其他三个属性有值,那么传递到后端的对象如下:
{
    cardNo: '哈哈哈',
    idCard: '哈哈哈',
    name: 'hahaha',
}
  • Note:这里不仅是Axios请求,jQuery封装的Ajax请求也一样。

  • Note:如果使用null取代undefined,得到的结果是:

{
	alipayAccount: null,
    cardNo: '哈哈哈',
    idCard: '哈哈哈',
    name: 'hahaha',
}

JSON.stringify()方法在序列化对象时针对nullundefined的差异

  • 通过上面的比较,可以发现undefinednull在某些场景下区别是存在的,虽然在很多场合下,难以区分它们。比如==相等符号就认为二者相等。
// undefined在序列化过程中会被忽略,当然不仅是undefined,也包括函数和Symbol,这里是想强调它和null的差异
JSON.stringify({
	foo: 'foo',
    bar: null,
    foobar: undefined
})
// "{"foo":"foo","bar":null}"
  • Note:这里简要总结下二者:null表示空值,undefined强调变量未定义、未声明