我有角应用程序,我想通过加号+在查询字符串,如:角网址加号转换为空间
http://localhost:3000/page?name=xyz+manwal
当我打这个URL其转换为:
http://localhost:3000/page?name=xyz%20manwal
其中%指的是空间。我怎样才能防止这种转换?
我有角应用程序,我想通过加号+在查询字符串,如:角网址加号转换为空间
http://localhost:3000/page?name=xyz+manwal
当我打这个URL其转换为:
http://localhost:3000/page?name=xyz%20manwal
其中%指的是空间。我怎样才能防止这种转换?
我找到了解决方案,并将其发布供将来参考。 Angular js将+
符号转换为%2B
。
下面的代码防止:
.config([
'$provide', function($provide) {
$provide.decorator('$browser', function($delegate) {
let superUrl = $delegate.url;
$delegate.url = (url, replace) => {
if(url !== undefined) {
return superUrl(url.replace(/\%2B/g,"+"), replace);
} else {
return superUrl().replace(/\+/g,"%2B");
}
};
return $delegate;
});
}
])
这是一个很常见的问题。您可以在application/x-www-form-urlencoded请求中正常传递它。没有其他请求将能够正确解析+。他们总是将它解析为%20而不是%2B。
您需要手动操作查询参数时,有2种方式:
欲了解更多信息,你应该reffer到HTHE以下堆栈溢出问题Android: howto parse URL String with spaces to URI object?和URL encoding the space character: + or %20?
这1A中常见的问题。该URL使用+
字符来分隔两个单词。为了在参数值中使用+
字符,需要在将参数值作为URL的一部分添加之前对其进行编码。 Javascript/TypeScript为该特定目的提供了一个encodeURI()
函数。
URL编码将字符转换为可通过Internet传输的格式,可以传输 。 [w3Schools Reference]
这里是你如何解决这个问题:
let encodedName = encodeURI('xyz+manwal');
let encodedURI = 'http://localhost:3000/page?name='+encodedName;
//.. OR using string interpolation
let encodedURI = `http://localhost:3000/page?name=${ encodedName }`;
以同样的方式,可以解码使用decodeURI()
方法的参数。
let decodedValue = decodeURI(encodedValue);
为什么你需要吗? –
我想在'xyz + manwal'中使用名称值,在给定的URL中保存'xyz manwal'。 – Manwal
它只是一个URL,无论你在哪里阅读,它都应该被正确解析为一个加号,你不能在URL中使用加号。阅读[本](https://stackoverflow.com/questions/2678551/when-to-encode-space-to-plus-or-20) –