Angular 6向PHP传递数组时查询字符串方括号编码问题
解决Angular HttpParams编码方括号的问题
嘿,这个问题我之前也碰到过!Angular的HttpParams默认会按照URL编码规则把特殊字符(比如方括号[])转成%5B%5D,这本身是符合标准的,但你的后端期望的是未编码的team[]参数名,下面给你两种可行的解决思路:
一、前端修改:让方括号不被编码
方法1:手动拼接查询字符串
直接构建完整的查询字符串,自己控制参数名的格式,同时记得对参数值做编码避免其他问题:
getPokemon(name: string) { // 对参数值进行编码,防止特殊字符破坏URL结构 const encodedName = encodeURIComponent(name); const queryString = `method=get_card_info&team[]=${encodedName}&team[]=${encodedName}&generation=7`; return this.http.get(`http://localhost/pokemon/ajax.php?${queryString}`); }
方法2:自定义HttpParams编码解码器
这种方法更贴合Angular的使用习惯,通过实现HttpParameterCodec接口,改写编码逻辑,让方括号保留原样:
import { HttpParameterCodec } from '@angular/common/http'; // 自定义编码类,处理方括号的编码逻辑 class CustomParamEncoder implements HttpParameterCodec { encodeKey(key: string): string { // 先正常编码,再把方括号的编码结果转回来 return encodeURIComponent(key) .replace(/%5B/g, '[') .replace(/%5D/g, ']'); } encodeValue(value: string): string { // 参数值正常编码即可 return encodeURIComponent(value); } decodeKey(key: string): string { return decodeURIComponent(key); } decodeValue(value: string): string { return decodeURIComponent(value); } } // 使用自定义编码器创建HttpParams getPokemon(name: string) { let myParams = new HttpParams({ encoder: new CustomParamEncoder() }); myParams = myParams.append('method', 'get_card_info'); myParams = myParams.append('team[]', name); myParams = myParams.append('team[]', name); myParams = myParams.append('generation', '7'); return this.http.get('http://localhost/pokemon/ajax.php', { params: myParams }); }
二、后端修改:适配编码后的参数
其实PHP本身是支持解析编码后的team%5B%5D参数的!PHP会自动把team[](不管是否编码)解析为数组,你可以直接打印$_GET['team']看看,应该能正常拿到包含两个Raichu的数组。
如果你的后端是自己手动解析请求参数(没有用PHP的自动解析),那只需要在解析时把%5B替换为[、%5D替换为],就能正常识别team[]参数了。
从规范角度来说,URL编码特殊字符是符合RFC标准的,后端适配这种情况会更通用,毕竟大部分HTTP客户端都会自动编码特殊字符;但如果后端不好修改,前端用上面的方法也能完美解决问题~
内容的提问来源于stack exchange,提问作者Drew Ingram
相关产品推荐
相关产品推荐

