2015-06-18 77 views
1

工作,我做了ajax調用使用jQueryjQuery的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); 
    } 
    }); 
}); 

在瀏覽器中我得到這個消息

error [object Object] - error 

我在Java

控制器Ajax調用
@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

問題在於參數串聯。

此代碼:

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; 
} 

包括其他參數,以及如果你喜歡。

+0

不修復,因爲我用我沒有使用任何值...所以它是空的。當我點擊按鈕,我看到我的警告框中的網址:http:// localhost:8080/lodgers/search。瀏覽器將我移至url:index.html?srch-term =這似乎是我的html表單原因問題。 –

+0

什麼樣的警報框顯示你?代碼中有3個警報框。考慮成功的方法不叫他們2出來。另一個是錯誤警告框,它不顯示網址。 無論如何,請刪除searchParam「if語句」,以確保它沒有做任何事情。 –