Spring MVC + JQuery + Ajax Issue

2019-08-30 11:21发布

问题:

I'm trying to make an Ajax call to my Spring MVC app using a Jquery Ajax. The app controllers are working fine but I can't get this Ajax test controller to work. The alert is triggered but the call to the controller is never made. I've also tried using load, get, post. None of them call the server. Which makes me think I'm doing something obviously wrong. If I put the URL directly on the browser address bar, the controller is called.

If someone can guide me in the right direction or tell me what I'm doing wrong, I'd be grateful.

JavaScript

<html>
<head>
<script type="text/javascript" src="jquery-1.8.1.min.js"> </script>
<script type="text/javascript">
    function doAjax() {
        alert("did it even get here?");
        $.ajax({
            url : "simpleRequestTest.do",
            method: "GET",          
            success : function(response) {
                $('#show').html(response);
            }
        });
    }
</script>
</head>
<body>
    <h1>Simple Test </h1>
    <a href="javascript:doAjax();"> Simple Test </a>
    <br />
    <div id="show">...</div>
</body>
</html>

Controller

@RequestMapping("/simpleRequestTest")
public @ResponseBody String performSimple()  {
    return "Very Simple Test";
}   

回答1:

Can you check whether you use correct path for include the jquery-1.8.1.min.js.

I checked the code it's working file for me.



回答2:

I think you are missing dataType in ajax call

try this

function doAjax() {
        alert("did it even get here?");
        $.ajax({
            url : "simpleRequestTest.do",
            method: "GET",          
            success : function(response) {
                $('#show').html(response);
            },
            dataType: 'text'
        });
    }


回答3:

Just change url : "simpleRequestTest.do", to url : "simpleRequestTest", and method: "GET", to type: "GET",

I think the method is removed in the jquery version 1.5 and latest