2017-08-03 84 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){} 

感谢所有为您的关注

相关问题