本文介绍了angularjs序列化表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想序列化angularjs表单数据。以下是控制器code:
i wish to serialize the form data in angularjs. following is the controller code:
function SearchCtrl($scope, $element, $http) {
$scope.url = 'php/search.php';
$scope.submit = function() {
var elem = angular.element($element);
//var dt = $(elem.parent()).serialize();
console.log($(elem.parent()).serialize());
$http({
method: 'POST',
url: $scope.url,
data: 'first=hgf&last=ghfgh',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
//var elem = angular.element(e.srcElement);
//alert($(elem.parent()).serialize());
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
return false;
};
}
编辑:
<!DOCTYPE html>
<html ng-app>
<head>
<title>Search form with AngualrJS</title>
<script src="../angular-1.0.1.min.js"></script>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/search.js"></script>
</head>
<body>
<div>
<form ng-controller="SearchCtrl" ng-submit="submit()">
<label>Search:</label>
<input type="text" ng-model="keywords" placeholder="enter name...">
<input type="text" ng-model="desc" placeholder="enter description...">
<button type="submit">Search</button>
<p>Try for example: "php" or "angularjs" or "asdfg"</p>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
</body>
</html>
但没有被印在控制台上。我在哪里去了?
but nothing gets printed on the console. where am i going wrong?
推荐答案
从:
有关被列入序列化的字符串形式元素的值,
该元素必须有一个name属性。
在你的HTML的输入没有名字,所以连载
返回一个空字符串。东西解决这个问题像...
In your HTML inputs do not have names, hence serialize
returns an empty string. Fix this with something like...
<input type="text" name="keywords" ng-model="keywords" placeholder="enter name...">
<input type="text" name="desc" ng-model="desc" placeholder="enter description...">
和,顺便说一句,你不必包装角 $元素
到jQuery函数: $ element.serialize()
将工作正常。
And, btw, you don't have to wrap Angular $element
into jQuery function: $element.serialize()
would work ok.
这篇关于angularjs序列化表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!