我正在尝试以角度方式发布表单的帖子,但输入 testValue 并没有获得值。
有什么建议吗?
在angularJs控制器中:
//FORM
$scope.submitEditSyncSettingsForm = function () {
if ($("#editSyncSettingsForm").valid()) {
$http({
url: "data/postSyncSettings.aspx",
data: { testValue: 'some value' },
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
}).success(function (data) {
console.log(data)
}).error(function (err) { "ERR", console.log(err) })
}
};
.aspx代码
public partial class postSyncSettings : System.Web.UI.Page
{
protected string strResponse = "";
protected void Page_Load(object sender, EventArgs e)
{
strResponse = Request.Form["testValue"];
}
}
答案 0 :(得分:1)
问题是数据仍然作为JSON发送到正文中。你必须自己序列化它。您可以使用this article ...
中的serializeData()
功能
$scope.submitEditSyncSettingsForm = function () {
$http({
url: "data/postSyncSettings.aspx",
data: serializeData({ testValue: 'some value' }),
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function (data) {
console.log(data)
}).error(function (err) {
"ERR", console.log(err)
})
};
// http://www.bennadel.com/blog/2615-posting-form-data-with-http-in-angularjs.htm
function serializeData(data) {
// If this is not an object, defer to native stringification.
if (!angular.isObject(data)) {
return ((data == null) ? "" : data.toString());
}
var buffer = [];
// Serialize each key in the object.
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[name];
buffer.push(
encodeURIComponent(name) +
"=" + encodeURIComponent((value == null) ? "" : value));
}
// Serialize the buffer and clean it up for transportation.
var source = buffer.join("&")
.replace(/%20/g, "+");
return (source);
}
答案 1 :(得分:0)
1)服务器上传递的数据应转换为URL编码的字符串
可以使用以下代码执行此操作:
$.param($scope.formData)
2)对于表单发布,您应该使用ng-sumbit
指令并进行验证,您可以使用$invalid/$valid
表单的属性。
$scope.processForm = function() {
$http({
method: 'POST',
url: '...your URL...',
data: $.param($scope.formData), // pass in data as strings
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function (data) {
console.log(data);
if (data.Status == "Success") {
//...
} else {
//...
}
});
};
<form name="myForm" ng-submit="processForm()">
......
<input type="submit" value="Send Text" ng-disabled="myForm.$invalid">