2017-08-03 81 views
1

我送使用AJAX和我的Spring MVC的控制器越來越null價值形式的數據,但如果我用Postman它將很好地工作。不知道爲什麼AJAX表單數據發送空到MVC控制器

這裏是我的Ajax調用:

$.ajax({ 
    type: "post", 
    url:"http://localhost:8080/fivenet/mobile/api/login", 
    crossDomain: true, 
    data: JSON.stringify(formData), 
    dataType: 'json', 
    contentType: 'text/html;charset=UTF-8', 
    //contentType: 'application/json;charset=utf-8', 
    beforeSend: function(xhr){ 
    }, 
    success: function(msg){ 
     console.log('sucess'); 
    }, 
error: function(msg){} 

這裏是我的控制器:

@CrossOrigin(origins = "*", maxAge = 3600) 
@RequestMapping(value = "create-account", method = RequestMethod.POST) 
public @ResponseBody RespondMessage createAccount(
     @RequestParam(value = "data", required = true) String dataString, 
     HttpServletRequest request) throws Exception { 

    RespondMessage responsed = new RespondMessage(); 
    headers = new HttpHeaders(); 
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); 
    JSONObject data = new JSONObject(dataString); 
return responsed; 
} 
+0

是否錯誤在JavaScript控制檯中發生的呢?你能準確地發佈你在POSTman中使用過的參數嗎? – matthewninja

+0

是的,它返回500,當我在調試模式下運行我的彈簧時,「String dataString」返回null。參數看起來像這樣{username}:「[email protected]」, 「password」:「12345」 } –

+0

你是如何填充'formData'的?初始化它的代碼在哪裏? –

回答

0

試試這個代碼:

var formData = {"username" : "username", "password" : "password"}; 

$.ajax({ 
    type: "POST", 
    url: "http://localhost:8080/fivenet/mobile/api/login", 
    data: JSON.stringify(formData), 
    dataType: 'json', 
    contentType: 'application/json;charset=utf-8', 
    beforeSend: function(xhr){ 
    }, 
    success: function(data){ 
     alert(data) 
    }, 
    failure: function(errMsg) { 
     alert(errMsg); 
    }, 
    error: function(errMsg){ 
     alert(errMsg); 
    } 
+0

當我嘗試@Chandra Kumar方法時,我得到這個:XMLHttpRequest無法加載http:// localhost:8080/webservices/PodcastService.asmx/CreateMarkers。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。因此不允許原產地'null'訪問。 –

+0

更新您的登錄Web服務URL:'http:// localhost:8080/fivenet/mobile/api/login' –

+0

檢查我已更新.. –

0

我終於解決了這個問題。它是我爲我的數據提供服務的方式。

$.ajax({ 
    type: 'POST', 
    url: "http://localhost:8080/fivenet/mobile/api/login", 
    crossDomain: true, 
    data: {"data": JSON.stringify(formData)},*** This is where the error is 
    dataType: 'json', 
    beforeSend: function(xhr){ 

    }, 
    success: function(msg){ 
     console.log('sucess'); 
    }, 
error: function(msg){} 

感謝所有爲您的關注

相關問題