使用Angular Post功能不执行操作

时间:2014-03-26 18:37:18

标签: javascript angularjs

我在这里使用带有struts的Angular,而且我是Angular的新手。

我有一个控制器( Controller.js ),我使用post方法调用动作类( CartAction )。

从controller.js中的帖子调用/StrutsAngular/ControllerAction.do操作时,我没有发现任何错误。

但是动作类没有执行,甚至没有执行system.out.println。 当我在成功功能中添加警报时,我能够获得输入页面。 当我给出了错误的路径时,我进入了错误功能。

我无法理解为什么不调用这个动作。

如果在这种情况下,我还有另一个澄清 - >如果调用该动作,我可以获得响应数据。

早些时候我使用过jQuery,我也提供了我使用的示例代码。 我们怎样才能以类似的方式使用AngularJS

请提供帮助,并在收到进一步信息时告诉我。

提前感谢您的答案。

Controller.js

function Controller($scope,$http) {

 $http.post('/StrutsAngular/ControllerAction.do').
        success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        alert("Success :: "+data);
         }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("Error :: "+data);
    });


}

行动类

public class CartAction extends org.apache.struts.action.Action {


    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        System.out.println("Entering Shop Cart Action");

    List<Object> objectList= new ArrayList<>(); 

    CartDto cartDto = new ShopingCartDto();
        cartDto.setSno(1);
        cartDto.setTitle("Title One");

    objectList.add(cartDto);


        response.setHeader("cache-control","no-cache");
        response.setContentType("text/json");
        PrintWriter out = response.getWriter();

    JSONArray jsonArray = JSONArray.fromObject(objectList);
        out.println(jsonArray.toString());

        return null;
    }


}

Jquery的

function onSubmit(){
 var url = "/StrutsAngular/ControllerAction.do";
 var formID = document.getElementById('formId');
 var forwardUrl = "/StrutsAngular/ControllerAction.do";

}

function doAjaxPost(formId,url,forwardUrl){

    var data = $("#"+formId+" :input").serializeArray();
    $.ajax({
    type: "POST",
    url: url,
    data: data,
    beforeSend: function(jqXHR, settings){

        var value = "Please Wait until progressing!";
        document.getElementById('progress').innerHTML=value;               
    },
    success: function(json){


     var message=json[0].message;


    },
    error: function(jqXHR, textStatus, errorThrown){

        if(jqXHR.status==500){
            document.getElementById('errorMessage').innerHTML=errorThrown;
        }

    },
    complete: function(jqXHR, textStatus){
        document.getElementById('progress').innerHTML="";

        if(jqXHR.status==500){

            var message = textStatus;
            document.getElementById('errorMessage').innerHTML=message;

        }

    }
});

}

JSP

<%-- 
    Document   : Cart
    Created on : 25 Mar, 2014, 5:14:42 PM
    Author     : Arun
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html ng-app>
    <head>
        <title>Cart</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <script src="js/lib/angularjs-1.0.2/angular.js"></script>
        <script src="js/lib/controllers/controllers.js"></script>
        <link href="js/lib/bootstrap/css/bootstrap.css" rel="stylesheet">
    </head>
    <body ng-controller='Controller'>

       <div class="container">


           <form name="shoppingForm" id="formId">

                <table class="table table-striped table-hover">
                    <caption></caption>
                    <thead>
                       <tr>
                        <th>S No</th>
                        <th>Item</th>
                       </tr> 
                    </thead>

                    <tr ng-repeat='item in items | orderBy:title | filter:search' >
                         <td ><input ng-model='item.sno' class="form-control" size="3" placeholder="Quantity" maxlength="3" required></td>
                        <td ><input ng-model='item.title' class="form-control" size="10" maxlength="10" placeholder="Item Name" required></td>
                    </tr>
                </table>
                <div><button class="btn btn-lg btn-success btn-block">Submit</button></div>
           </form>

       </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

好的,你有一些问题正在发生,而且大多数问题似乎都是对Angular如何运作的误解。从jQuery背景中有很多关于“思考角度”的帖子:

"Thinking in AngularJS" if I have a jQuery background?

到目前为止,根据您的代码为您提供一些细节:

首先,您需要创建一个分配了ng-app属性的app(angular.module)。例如:

 var myApp = angular.module('myApp',[]); // this creates a new angular module named "myApp";

 <html ng-app="myApp"> // this will bootstrap your myApp module at the html DOM element once the domIsReady event fires

其次,您需要在模块上使用Angular定义控制器,并传递一个函数。 Angular有experimental "Controller as" syntax但我建议在尝试之前以标准方式进行。

myApp.controller('myCtrl', function ($scope,$http) {

 $http.post('/StrutsAngular/ControllerAction.do').
        success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        alert("Success :: "+data);
         }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("Error :: "+data);
    });
});

<div ng-controller="myCtrl">

最后,传递给controller()的函数只会被调用一次,并且只能在它被某个地方使用之后调用。因此,在这个示例中,绑定到DIV会在加载DOM时产生单个$ http.post。它不会做任何其他事情。我假设这只是你测试它到达那里。对于“真实”代码,您将通过$ scope公开某些函数,并从您的视图中调用它们:

myApp.controller('myCtrl', function ($scope,$http) {
   $scope.sendData = function() {
     $http.post(.....your other code....);
   }
});

<div ng-controller="myCtrl"><a ng-click="sendData()">send data</a></div>