2013-02-22 61 views
0

我有以下jQuery腳本:我應該從ajax調用的服務器端方法返回什麼?

$(document).ready(function() { 
    $("#resendActivationEmailLink").bind("click", function(event) { 
     $.get($(this).attr("href"), function() { 
      $("#emailNotActivated").html("<span>not yet activated. email sent!</span>"); 
     }, "html"); 
     event.preventDefault(); 
    }); 
}); 

基本上,當用戶點擊在調用下面的服務器端方法的鏈接:

@RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET, produces = "application/json") 
    public @ResponseBody 
    String resendActivationEmail(@PathVariable("token") String token) { 
     preferencesService.resendActivationEmail(token); 
     return "dummy"; 
} 

和一些業務邏輯是在服務器上執行,但除了ajax成功或ajax失敗之外,服務器在客戶端/瀏覽器端沒有實際結果

現在什麼我真的不知道什麼是我的服務器端方法應該返回!

目前它只是返回字符串dummy,但當然這只是暫時的。我應該去沒有返回類型(void)或null或其他?

請注意,我可以更改數據類型 jQuery get方法的參數。

編輯:

我已經改變了我的服務器端的方法如下:

@RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET) 
    public @ResponseBody void resendActivationEmail(@PathVariable("token") String token) { 
     preferencesService.resendActivationEmail(token); 
    } 

@ResponseBody是必需的,因爲這是一個Ajax調用。

+1

這真的沒關係,不需要是任何類型的返回。 – 2013-02-22 16:41:11

+1

返回的數據作爲參數傳遞給回調函數。由於你的回調函數沒有任何參數,它忽略了這一點。 – Barmar 2013-02-22 16:42:02

+0

如果函數返回布爾型「true」或「false」,驗證會很好。 preferencesService函數返回什麼?如果它返回一個布爾值就返回該函數返回的任何值。然後在你的jQuery中,你可以告訴用戶郵件是否真的被髮送,或者發送給某個地方的日誌。 – 2013-02-22 16:42:39

回答

1

在這種情況下返回一個虛擬值沒有意義。如果你沒有做與返回任何有價值的東西,那麼你可以做這樣的事情:

@RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET) 
@ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT) 
public void resendActivationEmail(@PathVariable String token) { 
    preferencesService.resendActivationEmail(token); 
} 

將會有一個204響應代碼,而不是200但應該罰款。

1

我假設你從服務器返回JSON(從你的服務器代碼:produce =「application/json」)。

既然你不在乎返回的是什麼,即你沒有在你的回調函數中處理返回值,在$ .get之後,你可以返回「{}」,或者如果你想處理響應你可以用類似的東西:

{ "success": true } 
// or 
{ "error": "Error messages here" } 
相關問題