我有一个JSON对象,并使用HttpParams传递它,但它隐蔽+到空间并发送到后端。我尝试了所有可能的方法,但是没有人为JSONObject字符串解决它。
this.updateUser({"name":"ABC","mobile": "+911234567890","text":"1 + 2 = 3"});
public updateUser(myObj) {
const body = new HttpParams().set('user_object', JSON.stringify(myObj));
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
当我在网络中检查时,包含+字符的对象会自动转换为空间。
这是一个普遍的问题。+
URL使用该字符分隔两个单词。为了+
在参数值中使用字符,您需要先对参数值进行编码,然后再将其添加为URL的一部分。Javascript / TypeScript提供了encodeURI()
用于该特定目的的功能。
URL编码将字符转换为可以通过Internet传输的格式。[w3Schools参考]
这是解决此问题的方法:
let mobile = encodeURI("+911234567890");
let text = encodeURI("1 + 2 = 3");
this.updateUser({"name":"ABC","mobile": mobile,"text":text});
public updateUser(myObj) {
const body = new HttpParams().set('user_object', JSON.stringify(myObj));
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
要么
您可以在内部对updateUser()方法进行编码:
this.updateUser({"name":"ABC","mobile": "+911234567890","text":"1 + 2 = 3"});
public updateUser(myObj) {
let encodedJson = encodeURI(JSON.stringify(myObj));
const body = new HttpParams().set('user_object', encodedJson);
return this.http.post(url, body, {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
});
}
要么
+
在发送到服务器之前,使用正则表达式替换:
let jsonData = JSON.stringify(myObj);
jsonData = jsonData.replace(/\+/gi, '%2B');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句