Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - How do I post parameter on d3.json?

I'm using d3.json to get a dynamic data.

d3.json("/myweb/totalQtyService.do", function(json) {

    drawChart(json);
});

How do I post parameter on d3.json? i.e.

data : { year: "2012", customer: "type1“ }

Any idea pass those parameter on post? not url parameter /myweb/totalQtyService.do?year=2012&customer=type1

I tried such below, but couldn't make it work. because the data structure so different

d3.json => [Object, Object, Object, Object]

$.ajax => {entity_name: "ACTIVA"entity_tar_val: 350entity_val: 400level: 1_proto_: Object},...

$.ajax({ 
  type: "POST", 
  url: url,

  // parameter here
  data : {year: "2012", customer: "type1“},
  success: function(json){
       // console.log(json);
       **drawChart(json);**
  } ,
  error:function (request, err, ex) {
  }
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...