【问题标题】:Http status 404 (Not Found) on jquery ajax GET to spring controller?jquery ajax GET到spring控制器的Http状态404(未找到)?
【发布时间】:2014-07-26 18:55:37
【问题描述】:

我的 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 映射到/hostel。所以网址是/hostel/country?countryName=%27&amp;Albania%27&amp;&amp;geonameId=783754

当我在 chrome 浏览器中输入时

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

它按预期返回 json 响应!!!

但我想通过以下使用 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);
            }
            });

你猜这根本行不通。 Http 状态 404 (Not Found) 返回到error: handler。

我该如何解决这个问题?

【问题讨论】:

    标签: java jquery ajax spring-mvc


    【解决方案1】:

    ajax 调用中的url 是相对于主机名的。您需要添加您的 Web 应用程序上下文

    url : '/HostMe/hostel/country',
    

    【讨论】:

    • 非常感谢您的回复!我更改了网址,它开始工作了。
    • 为什么当我将您的网址设置为&lt;spring:url&gt; 时它不起作用并打印unexpected token &lt;。网址/hostel/country 也不适用于&lt;spring:url&gt;。我尝试了 htmlEscape 和 javascriptEscape 但它没有帮助。只有在 ajax 调用中设置你的 url 才有效。
    • @volo 你能用你想要做什么来更新你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 2022-06-12
    • 2020-07-21
    • 1970-01-01
    • 2020-08-15
    • 2021-03-14
    • 1970-01-01
    • 2019-12-02
    • 2019-07-30
    相关资源
    最近更新 更多