如何在angularjs中传递参数到$ http?

假设我有两个input框,相应的ng模型为fname和lname。 如果我将http请求称为:

$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}}) 

它会调用的url:

 /search?fname=fname&lname=lname 

我在后端(python)得到的错误是:

 cannot concatenate str and nontype objects. 

这些参数是否不作为string发送? 如果没有,如何解决这个问题?

这是你如何做到的:

 $http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}}) .then(function (response) { /* */ })... 

Angular负责编码参数 。

Maxim Shoustin的答案不起作用( {method:'GET', url:'/search', jsonData}不是一个有效的JavaScript文字),JeyTheva的答案虽然简单,但是很危险,因为它允许XSS(不安全的值不会被转义你连接它们)。

build立url'/search'作为string。 喜欢

 "/search?fname="+fname"+"&lname="+lname 

其实我没有用

  `$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})` 

但我确定“参数”应该是JSON.stringifyPOST

 var jsonData = JSON.stringify( { fname: fname, lname: lname } ); 

后:

 $http({ method:'GET', url:'/search', params: jsonData }); 

这是一个简单的mathed从路由提供者传递值

 //Route Provider $routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'}); //Controller $http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true}) .then(function(res){ //.... }) 

我们可以使用input数据作为参数在HTML文件中使用ng-model来绑定input字段的值。

 <input type="text" placeholder="Enter your Email" ng-model="email" required> <input type="text" placeholder="Enter your password " ng-model="password" required> 

并在js文件中使用$ scope来访问这些数据:

 $scope.email=""; $scope.password=""; 

控制器function将是这样的:

  var app = angular.module('myApp', []); app.controller('assignController', function($scope, $http) { $scope.email=""; $scope.password=""; $http({ method: "POST", url: "http://localhost:3000/users/sign_in", params: {email: $scope.email, password: $scope.password} }).then(function mySuccess(response) { // a string, or an object, carrying the response from the server. $scope.myRes = response.data; $scope.statuscode = response.status; }, function myError(response) { $scope.myRes = response.statusText; }); });