如何在 HTML 中从 AngularJS 模板调用 encodeURIComponent?

htmlweb developmentfront end technology更新于 2024/8/10 5:00:17

在本文中,我们将学习如何在 HTML 中从 AngularJS 模板调用 encode URI 组件。

每当 URI 中出现某个字符时,encodeURIComponent() 函数都会将其替换为一个、两个、三个或四个代表该字符 UTF-8 编码的转义序列(对于由两个"代理"字符组成的字符,只会替换四个转义序列)。

语法

以下是 encodeURIComponent 的语法

encodeURIComponent(uriComponent)

Uricomponent

任何对象,包括字符串、数字、布尔值、null 或 undefined。 uriComponent 在编码之前会被转换为字符串。

为了更好地理解,我们来看以下示例。

示例 1

在下面的示例中,我们使用 encodeURIcomponent

<!DOCTYPE html>
<html>
<body>
   <p id="tutorial"></p>
   <script>
      let uri = "https://www.cainiaomax.com/index.htm";
      let encoded = encodeURIComponent(uri);
      document.getElementById("tutorial").innerHTML = encoded;
   </script>
</body>
</html>

运行上述脚本后,将弹出输出窗口,显示我们在上述脚本中使用的 URL 的编码 URL。

示例 2

在下面的示例中,我们使用函数 encodeURIcomponent(string) 对 URL 参数进行编码。

<!DOCTYPE html>
<html>
<head>
   <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
   <script>
      var myApp = angular.module("mytutorials", []);
      myApp.controller("mytutorials1", function($scope) {
         $scope.url1 = 'https://www.cainiaomax.com/index.htm';
         $scope.url2 = '';
         $scope.encodeUrlStr = function() {
            $scope.url2 = encodeURIComponent($scope.url1);
         }
      });
   </script>
</head>
<body>
   <div ng-app="mytutorials">
      <div ng-controller="mytutorials1">
         <button ng-click ="encodeUrlStr()" >Encode URL</button>
         <br>
         URL1 = {{url1}}<br>
         URL2 = {{url2}}
      </div>
   </div>
</body>
</html>

脚本执行时,将生成由 url1 和 url2 组成的输出(url2 为空),并在网页上显示一个 encodeURL 按钮。

如果用户点击 encodeURL 按钮,url1 中提供的 url 将被编码并显示在 url2 中。


相关文章


有用资源