Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用AngularJS$location从URL中的查询字符串获取值_Javascript_Angularjs - Fatal编程技术网

Javascript 使用AngularJS$location从URL中的查询字符串获取值

Javascript 使用AngularJS$location从URL中的查询字符串获取值,javascript,angularjs,Javascript,Angularjs,关于$location.search,用户表示 在没有任何参数的情况下调用时,返回当前url的搜索部分(作为对象) 在我的URL中,我的查询字符串有一个参数?test_user_bLzgB,没有值。另外,$location.search()返回一个对象。如何获取实际文本?Angular不支持此类查询字符串 URL的查询部分应该是一个&分隔的键值对序列,因此可以完美地解释为对象 根本没有API来管理不表示键值对集的查询字符串。不确定自接受的答案被接受以来是否已更改,但这是可能的 $location

关于
$location.search
,用户表示

在没有任何参数的情况下调用时,返回当前url的搜索部分(作为对象)


在我的URL中,我的查询字符串有一个参数
?test_user_bLzgB
,没有值。另外,
$location.search()
返回一个对象。如何获取实际文本?

Angular不支持此类查询字符串

URL的查询部分应该是一个
&
分隔的键值对序列,因此可以完美地解释为对象


根本没有API来管理不表示键值对集的查询字符串。

不确定自接受的答案被接受以来是否已更改,但这是可能的

$location.search()
将返回与查询字符串相同的键值对对象。没有值的键只是作为true存储在对象中。在这种情况下,对象将是:

{"test_user_bLzgB": true}
您可以使用
$location.search()直接访问此值。test\u user\u bLzgB

示例(使用较大的查询字符串):


注意:由于散列(它将创建一个新的fiddle),此fiddle在不支持js历史记录的浏览器中不起作用(如果只需要将查询字符串视为文本,则在IE中不起作用,可以使用:
$window.location.search
$location.search()
返回一个对象,该对象由作为变量的键和作为其值的值组成。 因此:如果您这样编写查询字符串:

?user=test_user_bLzgB
您可以很容易地获得如下文本:

$location.search().user
如果您不想使用键,比如?foo=bar,我建议使用散列#test_user_bLzgB

和呼唤

$location.hash()
将返回“test_user_bLzgB”,这是您希望检索的数据

其他信息:

如果使用了查询字符串方法,并且得到了一个带有$location.search()的空对象, 这可能是因为Angular正在使用hashbang策略而不是html5策略。。。 要使其工作,请将此配置添加到模块中

yourModule.config(['$locationProvider', function($locationProvider){
    $locationProvider.html5Mode(true);    
}]);

首先,使用适合我的#?q=string正确设置URL格式以获取查询字符串

http://localhost/codeschool/index.php#?foo=abcd
将$location服务注入控制器

app.controller('MyController', [ '$location', function($location) { 

    var searchObject = $location.search();

    // $location.search(); reutrn object 
    // searchObject = { foo = 'abcd' };

    alert( searchObject.foo );

} ]);

所以输出应该是abcd

您也可以使用这个

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var queryValue = getParameterByName('test_user_bLzgB');

在我的NodeJS示例中,我有一个url“localhost:8080/Lists/list1.html?x1=y”,我想遍历它并获取值

为了使用$location.search()获得x1=y,我做了一些事情

  • 将源脚本添加到angular-route.js
  • 将“ngRoute”注入到应用程序模块的依赖项中
  • 配置您的locationProvider
  • 为$location添加基本标记(如果不添加,则search().x1将不返回任何内容或未定义。或者,如果基本标记包含错误信息,则浏览器将无法在脚本src中找到.html所需的文件。始终打开页面的查看源以测试文件位置!)
  • 调用位置服务(search())
  • 我的list1.js

        var app = angular.module('NGApp', ['ngRoute']);  //dependencies : ngRoute
        app.config(function ($locationProvider) { //config your locationProvider
             $locationProvider.html5Mode(true).hashPrefix('');
        });
    
        app.controller('NGCtrl', function ($scope, datasvc, $location) {// inject your location service
            //var val = window.location.href.toString().split('=')[1];
            var val = $location.search().x1;    alert(val);
            $scope.xout = function () {
               datasvc.out(val)
               .then(function (data) {
                  $scope.x1 = val;
                  $scope.allMyStuffs = data.all;
               });
            };
            $scope.xout();
        });
    
    我的list1.html

    <head>
        <base href=".">
        </head>
    <body ng-controller="NGCtrl">
    <div>A<input ng-model="x1"/><br/><textarea ng-model="allMyStuffs"/></div>
    <script src="../js/jquery-2.1.4.min.js"></script>
    <script src="../js/jquery-ui.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/ui-bootstrap-tpls-0.14.3.min.js"></script>
    <script src="list1.js"></script>
    </body>
    
    
    A

    指南:

    如果您的
    $location.search()
    不起作用,请确保您具有以下功能:

    1)
    HTML5模式(true)
    在应用程序的模块配置中配置

    appModule.config(['$locationProvider', function($locationProvider) {
       $locationProvider.html5Mode(true);
    }]);
    
    2)
    出现在您的HTML中

    <head>
      <base href="/">
      ...
    </head>
    
    
    ...
    
    参考资料:


  • 我的修复更简单,创建一个工厂,并作为一个变量实现。比如说

    angular.module('myApp',[])
    //这是一家定制工厂。复制工厂并在控制器中实施
    .factory(“searchCustom”,函数($http,$log){
    返回{
    参数:函数(参数){
    paramsResult=[];
    params=params.replace('(','').replace('),'').split(“&”);
    用于(参数中的x){
    paramsKeyTmp=params[x]。拆分(“=”);
    //有争议的矢量参数结果
    如果(paramsKeyTmp[1]!='&¶msKeyTmp[1]!='&&
    paramsKeyTmp[1]!==null{
    参数结果推送(参数[x]);
    }
    }
    返回paramsResult;
    }
    }
    })
    .controller(“SearchController”,函数($scope、$http、$routeParams、$log、searchCustom){
    $ctrl=这个;
    var valueParams=searchCustom.valuesParams($routeParams.value);
    valueParams=valueParams.join('&');
    $http({
    方法:“获取”,
    url:webservice+“q?”+valueParams
    }).then(函数成功回调(响应){
    data=response.data;
    $scope.cantEncontrados=data.length;
    $scope.dataSearch=数据;
    },函数errorCallback(响应){
    console.log(response.statusText);
    })
    })
    
    
    非常晚的回答:(但对于需要帮助的人, 这也行得通:)URLSearchParams让我们看看如何使用这个新API从位置获取值

    //假设“?post=1234&action=edit”

    仅供参考:不支持IE 从而不是从URLSearchParams使用此函数

    urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                          .exec(window.location.search);
    
        return (results !== null) ? results[1] || 0 : false;
    }
    
    console.log(urlParam('action')); //edit
    

    你得到了什么东西?你是否有一把能证明你所面临问题的琴弓或小提琴?当您使用
    $location.search()
    时,您是正确的,但我想检查您调用它时得到的“对象”…我不知道它是什么对象。我尝试枚举属性,但似乎没有。不确定如何使用小提琴检查查询字符串。如Naresh所述,
    $locationProvider
    urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                          .exec(window.location.search);
    
        return (results !== null) ? results[1] || 0 : false;
    }
    
    console.log(urlParam('action')); //edit