简体   繁体   中英

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

My spring controller contains such get handler :

@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 . So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754

When I type in chrome browser

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

It returns json response as expected!!!

But I want to access this url with the following ajax call made with jquery:

 $.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 .

How can I solve this?

The url in the ajax call is relative to the hostname. You need to add your web application context

url : '/HostMe/hostel/country',

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