JQuery $ .getJSON无法在Spring MVC中运行

时间:2012-03-08 05:21:37

标签: jquery ajax spring-mvc getjson

我正在尝试在我的基于MVC的Spring应用程序中使用jquery进行ajax调用。

下面是我的ajax控制器

@Controller
@RequestMapping("/ajax/*")
public class AjaxController extends BaseController {

    private static Logger log = Logger.getLogger(AjaxController.class);

    @Autowired
    private ICountryService countryService;

    @RequestMapping(value = "/findCountriesByRegionId", method = RequestMethod.GET)
    public @ResponseBody
    List<Country> findCountriesByRegionId(
            @RequestParam(value = "regionId") int regionId) {
        log.info("finding countries by region id [" + regionId + "]");
        List<Country> countryList = countryService.findByRegionId(regionId);
        return countryList;
    }

以下是我的javascript代码

    function populateCountriesByRegionId(regionId) {
    alert("11");
    $.getJSON("ajax/findCountriesByRegionId", {
        regionId : regionId
    }, function(countryList) {
        alert("2");
        $("#countryId").empty();
        // $("#countryId").html("");
        var options = $("#countryId");
        options.append($("<option />").val('0').text(""));
        $.each(countryList, function() {
            options.append($("<option />").val(this.countryId).text(
                    this.countryName));
        });
    });
}

但我的控制器方法根本没有被调用。

当我在页面上的网址为http://localhost/myApp/emp/new时,我的ajax网址就像ajax / findCountriesByRegionId一样,它给出了错误,指出没有地址为url myapp / emp / ajax / findCountriesByRegionId。

为什么检查url myapp / emp / ajax / findCountriesByRegionId。它应该是myapp / ajax / findCountriesByRegionId

当我起诉url像/ ajax / findCountriesByRegionId(在开头添加/)时,没有任何反应。完全没有错误。没有调用控制器。

我希望将所有ajax方法放在一个控制器中,并在执行其他控制器(例如emp)时调用它们。

请帮忙。

1 个答案:

答案 0 :(得分:2)

  • 首先不要在页面中使用相对URL。 $.getJSON("/myApp/ajax/findCountriesByRegionId"
  • 秒在您的控制器的类级别的映射结尾没有/ *。只需/ajax
  • 第三,确保在尝试使用jquery命令之前,可以在给定url路径的情况下调用控制器,并确保json看起来像您期望的那样。将chrome指向http://localhost/myApp/ajax/findCountriesByRegionId?regionId=1