How Do I Post Parameter On D3.json?
Solution 1:
NOTE: This answer applies to an older version of d3.json, see JoshuaTaylor's comment below.
NOTE for d3v5: The original answer is increasingly out of date. d3 v5 uses the fetch API and promises rather than XMLHttpRequest.
You can set the method of the http request in the second parameter of any of the d3-fetch data getting functions e.g.
d3.csv("/path/to/file.csv", { method: 'POST' })
.then((data)=>{ /* do something with 'data' */ });
d3.json is a convenience method wrapping d3.xhr; it's hardwired to make GET requests.
If you want to POST you can use d3.xhr directly.
Something like this:
d3.xhr(url)
.header("Content-Type", "application/json")
.post(
JSON.stringify({year: "2012", customer: "type1"}),
function(err, rawData){
var data = JSON.parse(rawData);
console.log("got response", data);
}
);
Because no callback is specified in creation of the request object it's not sent immediately. Once received the JSON response can be parsed in the standard JavaScript way i.e. JSON.parse(data)
The documentation for d3.xhr is here.
Solution 2:
You could also try this:
d3.json(url,function(error, data) {
...
})
.header("Content-Type","application/json")
.send("POST", JSON.stringify({year: "2012", customer: "type1"}));
Solution 3:
Using d3-fetch in D3v5, it looks like
d3.json(url, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(query)
});
Where url
is the URL and query
is the content to post.
I found the answer in this question.
Solution 4:
If you want to make a request like an HTML form (using query parameters), then you would do:
d3.request("/path/to/resource")
.header("X-Requested-With", "XMLHttpRequest")
.header("Content-Type", "application/x-www-form-urlencoded")
.post("a=2&b=3", callback);
See the docs here: d3-request docs
If you want to convert a simple object to a query parameter string, then you can use the following function:
function obj2Params(params){
var str = "";
var amp = "";
for(var p inparams){
if(params.hasOwnProperty(p)) {
str += amp + encodeURIComponent(p) + "=" + encodeURIComponent(params[p]);
amp = "&";
}
}
return str;
}
Solution 5:
If you use struts you can define the url and the parameter:
<s:urlaction="jsondatatreeaction"var="jsonsearchTag"namespace="/data"><s:paramname="searchType"value="%{searchType}"></s:param></s:url>
.
.
.
d3.json('${jsonsearchTag}', function(error, flare) {
...
}
.
.
.
Post a Comment for "How Do I Post Parameter On D3.json?"