简体   繁体   English

jQuery ajax GET上的HTTP状态404(未找到)到Spring Controller吗?

[英]Http status 404 (Not Found) on jquery ajax GET to spring controller?

My spring controller contains such get handler : 我的spring控制器包含这样的get处理程序:

@RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody List<Region> getRegionsFor(@RequestParam(value = "countryName") String countryName,
            @RequestParam(value = "geonameId") Long geonameId) {
        logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
        RegionInfo regionInfo = restTemplate.getForObject(
                "http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
                RegionInfo.class, geonameId);
        return regionInfo.getRegions();
    }

@Controller is mapped to /hostel . @Controller映射到/hostel So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754 网址是/hostel/country?countryName=%27&Albania%27&&geonameId=783754

When I type in chrome browser 当我在Chrome浏览器中输入内容时

http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754

It returns json response as expected!!! 它按预期返回json响应!!!

But I want to access this url with the following ajax call made with jquery: 但是我想通过使用jquery进行以下ajax调用来访问此URL:

 $.ajax({
            headers : {
                'Accept' : 'application/json'                   
            },
            url : '/hostel/country',
            dataType : 'json',
            data : {countryName:"Albania",geonameId:783754},
            type : 'GET',
            async : true,
            success : function(response) {
                console.log("response=" + response.join(','));
            },
            error : function(errorData) {
                console.log("data on fail ");
                printObject(errorData);
            }
            });

As you guess this doesn't work at all. 如您所料,这根本不起作用。 Http status 404 (Not Found) is returned to error: handler . Http状态404(未找到)返回到error: handler。

How can I solve this? 我该如何解决?

The url in the ajax call is relative to the hostname. ajax调用中的url相对于主机名。 You need to add your web application context 您需要添加Web应用程序上下文

url : '/HostMe/hostel/country',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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