简体   繁体   中英

Can not make ajax call to server

I've tried to use ajax in Spring MVC App but it seems not working I searched for that and found many resources but as I'm not a pro I could not understand any of those, finally I found this tutorial as a grace and tried in Controller as

@RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
    public  @ResponseBody List<Bar> getBars(@RequestParam String bar, HttpServletResponse response) {
        return barService.findBarByName(bar);

    }

and javascript is

$(document).ready(function() {
    $(function() {
        $("#bar-search").autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: "/app/getBars",
                    type: "POST",
                    data: { term: request.term },

                    dataType: "json",

                    success: function(data) {
                        response($.map(data, function(v,i){
                            return {
                                        label: v.empName,
                                        value: v.empName
                                       };
                        }));
                    }
               });              
            }   
        });
    });
});

and finally my view.jsp is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="initial-scale=1.0, width=device-width" name="viewport">
    <title>Ask Question</title>
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"/></script>
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="/app/resources/js/autoComplete.js"></script>
    <script>
        if (window.jQuery) {  
            alert('jQuery is loaded');
        } else {
            alert('jQuery is not loaded');
        }                                   
    </script>
    <!-- css -->
    <link href="/app/resources/css/base.css" rel="stylesheet">

    <!-- favicon -->
    <!-- ... -->

    <!-- ie -->
        <!--[if lt IE 9]>
            <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
            <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->

</head>
<body>
<div class="form-group form-group-label">
     <div class="row">                                          
        <div class="col-md-10 col-md-push-1">                                                   
            <label class="floating-label" for="login-username">Bars</label>
                <input id="bar-search" name="bars" class="form-control" type="text" value=""/>
        </div>
     </div>
</div>
<script src="/crazy/resources/js/base.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/webfont.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/jquery.autocomplete.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
</body>
</html>

every thing is ok when app starts but when I write some text down in input I get error

在此处输入图片说明 can any one solve this error for me or tell me where am I wrong. sorry if my English is incorrect.

Ok... the first thing is that your service is configured wrongly.

Your service wants a @RequestParam, but in your ajax you are sending a json object which means you should be accepting a @RequestBody.

Also, if you are looking for a @RequestParam, you need to pass the value as part of the url like...

$.ajax({
    url: "/app/getBars?bar=" + request.term,
    type: "GET"          
    ( ... )
});   

@RequestMapping(value = "/getBars", method = RequestMethod.GET, produces = "application/json")
public  @ResponseBody List<Bar> getBars(@RequestParam(value = "bar", defaultValue = "abc", required = false) String bar, HttpServletResponse response) {
    return barService.findBarByName(bar);

}

or

$.ajax({
    url: "/app/getBars/" + request.term,
    type: "GET"          
    ( ... )
}); 

@RequestMapping(value = "/getBars/{bar}", method = RequestMethod.GET, produces = "application/json")
public  @ResponseBody List<Bar> getBars(@PathVariable String bar, HttpServletResponse response) {
    return barService.findBarByName(bar);

}

For a post.

First create a bean.

public class MyRequestBean implements Serializable{

    private static final long serialVersionUID = 1L;

    private String bar;

    public void setBar(String bar){
         this.bar = bar;
    }

    public void getBar(){
        return this.bar;
    }

}

and then write your service like this...

@RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public  @ResponseBody List<Bar> getBars(@RequestBody MyRequestBean bean, HttpServletResponse response) {
    return barService.findBarByName(bean.getBar());

}

$.ajax({ 
    url: "/app/getBars/,
    type: "POST",
    data: JSON.stringify({bar : request.term})
    ( ... )
}); 

NOTE: never have the verbs defining your service.

For example, /getBars can be changed to just /bars and let the HTTP protocol (GET, POST, PUT or DELETE etc..) descide which operation you are trying to perform.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM