【问题标题】:$.ajax to call post rest service$.ajax 调用 post rest 服务
【发布时间】:2012-04-02 22:22:25
【问题描述】:

用于调用rest服务的ajax代码

   $
.ajax({
    type : "post",
    url : 'http://service/status',
    success : function(dt) {
                    $.each(dt, function(key, val) {
            var tr = $('<tr></tr>');
            $.each(val, function(k, v) {
                $('<td>' + v + '</td>').appendTo(tr);
            });
            tr.appendTo("#tableID");
        });

    },
    error : function(msg) {
        alert(msg.responseText);
    }

});

我想在请求正文中发送 json 数据,你能帮我看看在上面的代码中要添加什么

【问题讨论】:

  • 您想在标头或帖子正文中发送 JSON 数据?此 REST 服务是否与您的上述脚本位于同一域中?
  • $.ajax({ type : "post", url : 'service/status', headers: {'key': jsonvalue}, //etc.
  • 我希望它在请求正文中而不是在请求标头中发送

标签: jquery json jquery-ui


【解决方案1】:

如果你真的想在请求头中添加一些东西,那么你需要使用 jQuery 公开的“headers”选项或“beforeSend”事件。请参阅此处的文档:http://api.jquery.com/jQuery.ajax/

我猜你真正想要的是将数据添加到请求的正文中,你可以使用“数据”参数来做到这一点:

$.ajax({
    type : "post",
    url : 'http://service/status',
    data : {
        your: 'data here',
        someJSON: '{"foo":"bar","boo":"far"}'
    },
    success : function(dt) {
                    $.each(dt, function(key, val) {
            var tr = $('<tr></tr>');
            $.each(val, function(k, v) {
                $('<td>' + v + '</td>').appendTo(tr);
            });
            tr.appendTo("#tableID");
        });

    },
    error : function(msg) {
        alert(msg.responseText);
    }

});

如果我弄错了,并且您确实需要标头,那么只需将“数据”替换为“标头”即可...

【讨论】:

  • 但我希望数据在请求正文中而不是在请求标头中传递
  • 这是我的假设,也是这段代码的作用。您放入该“数据”属性的任何内容都将作为 POST 正文的一部分提供。
  • { "userId" : 12256, "start" : "2012-03-15", "end" : "2012-03-15", "Id" : 97050 } 是正确的数据命令让我知道是否有问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多