jQuery posting valid json in request body


http://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body




So according to the jQuery Ajax docs, it serializes data in the form of a query string when sending requests, but setting processData:false should allow me to send actual JSON in the body. Unfortunately I'm having a hard time determining first, if this is happening and 2nd what the object looks like that is being sent to the server. All I know is that the server is not parsing what I'm sending.

Using http client when posting an object literal {someKey:'someData'} it works. but using jQuery with data: {someKey:'someData'} it fails. Unfortunately when i analyze the request in safari, it says the message payload is [object Object] ... great... and in Firefox the post is blank...

When logging the body content on the java side it literally gets [object Object] so how does one send REAL json data??

Has anyone had experience with a Java service serializing json data in the request body, with the request sent from jQuery?

BTW here is the full $.ajax request:

$.ajax({
    contentType: 'application/json',
    data: {
        "command": "on"
    },
    dataType: 'json',
    success: function(data){
        app.log("device control succeeded");
    },
    error: function(){
        app.log("Device control failed");
    },
    processData: false,
    type: 'POST',
    url: '/devices/{device_id}/control'
});
share improve this question
 

1 Answer

up vote 167 down vote accepted

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

share improve this answer
 
 
so do I no longer need the processData: false using JSON.stringify() ? –  brad  Nov 11 '10 at 22:19
4 
@brad - correct, it won't matter after doing this because it's already a string, and in that case jQuery won't process it further. –  Nick Craver  Nov 11 '10 at 22:23 
 
worked like a charm, many thanks! Is it true then that all request bodies are expected to be strings that get parsed on the other end? –  brad  Nov 12 '10 at 14:28
 
@brad - yup, correct again :) –  Nick Craver  Nov 12 '10 at 14:35
 
Great answer Nick. Thanks! –  Kirk  Jan 14 '13 at 4:51

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值