2013-06-27 49 views
0

在服务器端,我有一个看起来像这样的方法:如何发布包含对象数组的JSON请求?

@POST 
@Path("/foods/{year}/{month}/{day}") 
@Consumes("multipart/mixed") 
@Produces("application/json; charset=UTF-8") 
@Transactional 
public boolean setFoodsForTheDay(@PathParam("year") int year, @PathParam("month") int month, 
    @PathParam("day") int day, @Multipart(value = "foodList", type = MediaType.APPLICATION_JSON) Food[] foodList) { 

    if (log.isDebugEnabled()) { 
    log.debug("list size={}", foodList.size()); 
    } 
    doStuff(foodList); 

} 

如果我在下面的POST请求发送到/食品/ 2013/06/26。将实际工作与阵列将得到解析正确:

Host: localhost:7777 
Accept: application/json 
Content-Type: multipart/mixed; boundary=---------------------------25819220131967 
Content-Length: 226 

-----------------------------25819220131967\r\n 
Content-Disposition: form-data; name="foodList"\r\n 
Content-Type: application/json\r\n 
\r\n 
[ {"id":null,"name":"Banana","recipe":null} ]\r\n 
-----------------------------25819220131967--\r\n 

正如你所看到的,在发送重要的一个多/混合(或者多/表单数据将工作太),因为这样我可以设置部分的内容类型,它会被正确解析。

这一切正常。现在的问题是,我需要使用jQuery(或任何其他Ajax工具)发送此请求,并且看起来不可能发送multipart/mixed?或者使用iframe有一些技巧,但仍不可能设置零件的Content-type

有没有人知道这个问题的解决方案?如何在JSON序列化中将对象数组发送到服务器?

回答

3

看起来这是不可能与jQuery,但我没有找到a blog它展示了如何用做旧的XMLHttpRequest。

这是我的Javascript代码现在,它完美的作品! :)

function sendFoodRequest() { 
    var xhr = new XMLHttpRequest(); 

    xhr.open("POST", 'http://localhost:7777/services/rest/foods/2013/06/25', true); 

    var boundary = '---------------------------'; 
    boundary += Math.floor(Math.random()*32768); 
    boundary += Math.floor(Math.random()*32768); 
    boundary += Math.floor(Math.random()*32768); 
    xhr.setRequestHeader("Content-Type", 'multipart/mixed; boundary=' + boundary); 
    var body = ''; 
    body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="foodList"' + '\r\n'; 
    body += "Content-Type: application/json\r\n\r\n"; 
    body += '[ {"id":null,"name":"Spinach","recipe":null} ]'; 
    body += '\r\n' 
    body += '--' + boundary + '--'; 
    xhr.setRequestHeader('Content-length', body.length); 
    xhr.onload = function() { } 
    xhr.send(body); 
} 
0

是的,你可以发送多/混合通过JQuery的阿贾克斯,但必须添加额外的东西:

cache: false, 
contentType: false, 
processData: false, 


$.ajax({ 
    url: 'php/test.php', 
    data: {name: "test1", age 5}, 
    cache: false, 
    contentType: false, 
    processData: false, 
    type: 'POST', 
    success: function(data){ 
     alert(data); 
    } 
}); 
+0

这似乎并不奏效。在Chrome下我得到“无效的媒体类型”的错误,而在Firefox下,一个非常长的错误就像“JavaScript组件没有命名的方法:”可用“'当调用方法...” 据我可以看到如果我正在尝试发送DELETE请求,并且我的浏览器不支持该功能,则会出现预期的错误...但是,在这种情况下,我只发送一个典型的POST请求。 – Csaba

相关问题