简体   繁体   English

jQuery如何使用JSON字符串数据构造Ajax POST请求

[英]How does jQuery construct an Ajax POST request with JSON string data

I'm trying to hit a web site endpoint from a Java servlet using HttpClient (v4.1). 我正在尝试使用HttpClient(v4.1)从Java servlet中访问网站端点。 The endpoint expects a post request containing parameters in a JSON string, from what I can tell. 据我所知,端点希望发布请求包含JSON字符串中的参数。 I say "from what I can tell" because I have some sample jquery production code that makes successful requests to the endpoint. 我说“根据我的判断”,因为我有一些示例jquery生产代码可以成功向端点发出请求。 It looks like this: 看起来像这样:

$.ajax({
    type: "POST",
    url: "some/u/r/l",
    data: "{'keyA':'valueA','keyB':'valueB','keyC':'valueC'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    ...

So I'm trying to replicate this behavior from a Java servlet using HttpClient, but I'm getting ambiguous 500's from the server, so I must be creating the request incorrectly. 因此,我尝试使用HttpClient从Java servlet复制此行为,但是我从服务器获取了500的模棱两可,因此我必须错误地创建了请求。 Can anyone tell me exactly what jQuery is doing in the above code. 任何人都可以告诉我jQuery在上述代码中到底在做什么。 I understand that using a JS object as value for data parameter will add the respective key-value pairs as URL parameters to the request, but what happens to the JSON string as in the above example? 我知道使用JS对象作为data参数的值会将相应的键值对添加为请求的URL参数,但是如上例所示,JSON字符串会发生什么情况? Where does it go? 去哪儿了?

The JSON string needs to be added to the request body. JSON字符串需要添加到请求正文中。 For HttpClient (4.1) this goes something like: 对于HttpClient(4.1),它类似于:

request.setEntity(new StringEntity(json, "application/json", HTTP.UTF_8));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM