Jquery Ajax调用返回错误,但使用curl

时间:2015-06-18 14:37:06

标签: jquery ajax debugging

我用jquery

进行ajax调用
<form class="navbar-form" role="search">
     <div class="input-group">
         <input type="text" class="form-control" placeholder="Rechercher" name="srch-term" id="srch-term">
         <div class="input-group-btn">
             <button id="lodgerSearch" type="button" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
         </div>
     </div>
</form>

$('#lodgerSearch').on('click', function (e) {
  var searchParam = $('#srch-term').val();
  var url = "http://localhost:8080/lodgers/search";

  if(searchParam!=""){
    url = "http://localhost:8080/lodgers/search?searchTemp=" + searchParam; 
  }

  jQuery.ajax({
    type: "GET",
    url: url,
    success: function (data, status, jqXHR) {
        alert(data);
        // do something
        alert("sucess");
    },
    error: function (jqXHR, status) {
        // error handler
        alert("error " + jqXHR + " -  " + status);
    }
  });
});

在浏览器中使用ajax调用我收到此消息

error [object Object] -  error

我在java中的控制器

@RequestMapping(value = "/lodgers/search", method = RequestMethod.GET)
public List<LodgerSearch> getAllLogders(@RequestParam(value = "inactiveLodger", required = false) boolean inactiveLodger, @RequestParam(value = "searchTerm", defaultValue="") String searchTerm) {
    return lodgerService.searchLodger(inactiveLodger, searchTerm);
}

如果我做curl localhost:8080 / lodgers / search 我得到了预期的结果

[{"lodgerId":1,"firstName":"Marc","lastName":"Collin","birthdate":"2015-06-17","nas":null,"nam":null,"buildingRoom":null},{"lodgerId":2,"firstName":"yvan","lastName":"Dubois","birthdate":"2015-06-18","nas":null,"nam":null,"buildingRoom":null}]

1 个答案:

答案 0 :(得分:1)

问题在于参数连接。

此代码:

if(searchParam!=""){
  url = "http://localhost:8080/lodgers/searchTemp?" + searchParam; 
}

不会调用http://localhost:8080/lodgers/search,而是调用http://localhost:8080/lodgers/searchTemp(不是参数)。

当你使用curl时,你传递了正确的url,所以它返回ok。

将上述代码更改为

if(searchParam!=""){
  url = "http://localhost:8080/lodgers/search?searchTemp=" + searchParam; 
}

如果您愿意,还可以包含其他参数。