我在前端使用angularjs。我在index.html上有两个输入框(即名字和姓氏)和一个按钮。在单击按钮(ng-click =“search()”)时,我要调用一个以名字和姓氏为参数的http GET请求。然后,我想在同一页面的其他DIV标签中显示响应。我将如何实现呢?
最佳答案
HTML:
<div ng-app="MyApp" ng-controller="MyCtrl">
<!-- call $scope.search() when submit is clicked. -->
<form ng-submit="search()">
<!-- will automatically update $scope.user.first_name and .last_name -->
<input type="text" ng-model="user.first_name">
<input type="text" ng-model="user.last_name">
<input type="submit" value="Search">
</form>
<div>
Results:
<ul>
<!-- assuming our search returns an array of users matching the search -->
<li ng-repeat="user in results">
{{user.first_name}} {{user.last_name}}
</li>
</ul>
</div>
</div>
Javascript:
angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.user = {};
$scope.results = [];
$scope.search = function () {
/* the $http service allows you to make arbitrary ajax requests.
* in this case you might also consider using angular-resource and setting up a
* User $resource. */
$http.get('/your/url/search', { params: user },
function (response) { $scope.results = response; },
function (failure) { console.log("failed :(", failure); });
}
}]);
关于angularjs - 如何在ng-click事件中调用http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18893497/