gpt4 book ai didi

javascript - AngularJS 成功 PUT 后进行不需要的 GET

转载 作者:行者123 更新时间:2023-12-02 16:39:33 25 4
gpt4 key购买 nike

总之,在我的 AngularJS 页面中,我放置并收到答案。现在 Angular 正在做一些事情,将表单字段放入 URL 中并执行相当于 GET 的操作。

详细来说,我的表格是这样的:

<body ng-app="userApp">
<div ng-controller="userController">
<form id="userForm" modelAttribute="userAttribute" action="">
<table>
<tr><td><input type="text" id="userName" ng-model="user.userName" /></td></tr>
<tr><td><input type="text" id="fullName" ng-model="user.fullName" /></td></tr>
<tr><td><button type="submit" ng-click="submitForm()">Submit</button></td></tr>
</table>
</form>
</div>
</body>

我的 Controller 是:

angular.module("userApp", [])
.controller("userController", ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.user = {};
$scope.msg = "";

$http.get('/sg/user/' + userId)
.success(function(data, status, headers, config) {
$scope.user = data;
$scope.error = "";

if(typeof $scope.user._id === "undefined") {
$scope.formTask = "Create New";
$document.prop('title', 'Create User');
} else {
$scope.formTask = "Edit";
$document.prop('title', '"Edit User');
}

})
.error(function(data, status, headers, config) {
$scope.user = {};
$scope.error = data;
});

$scope.submitForm = function()
{
$http.put('/sg/user/' + userId, $scope.user)
.success(function (data, status, headers, config)
{
$scope.msg = data;
})
.error(function (data, status, headers, config)
{
$scope.msg = "SUBMIT ERROR";
});
};
}]);

当我调用该页面时:

http://MYAPP/sg/user/edit/2

页面显示正常,填充了用户 #2 数据。当我单击“提交”时,$http.put() 被调用,并且(使用调试器)调用 .success() 函数,“数据”被我的“用户#2 更新成功”消息填充。

一旦 success() 退出,URL 栏就会填充以下内容:

http://MYAPP/sg/user/edit/2?userName=SecondUser&fullName=Second+User

并且 .controller() 被再次调用。就像页面被告知刷新一样,除了表单字段被填充,就像我发送了 GET 一样。

我在这里缺少什么?

TIA,杰罗姆。

最佳答案

您正在使用 ng-click,但没有什么可以阻止按钮的默认操作,即提交表单。

请改用以下内容。

<form ng-submit="submitForm()" ...>

或者将按钮的 type="submit" 更改为 type="button"

关于javascript - AngularJS 成功 PUT 后进行不需要的 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27623941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com