简体   繁体   English

如何在jquery ajax请求的data参数内表示一个json数组?

[英]How do I represent a json array within the data parameter in a jquery ajax request?

I am trying to post some data via ajax to our backend API, but the arrays within the json data get turned into weird things by jquery...for example, the backend (python) sees the jquery ajax data as a dict of two lists 我正在尝试通过ajax一些数据发布到我们的后端API,但是jQuery数据将json数据中的数组变成奇怪的东西...例如,后端(python)将jquery ajax数据视为两个列表的字典

{'subject': ['something'], 'members[]': ['joe','bob']} 

when it should be 什么时候应该

{'subject':'something','members':['joe','bob']}

The HTML Form extracted from a react component: 从react组件提取的HTML表单:

  <div class="the_form">
    <form onSubmit={this.handleSubmit}>
      <input type="textarea" ref="members" placeholder="spongebob, patrick" />
      <input type="submit" value="Add Thread" />
    </form>
  </div>

The jquery ajax code: jQuery ajax代码:

$.ajax({
        beforeSend: function(xhr, settings) {
            // csrf validation
        },
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: {subject: "something", members: ["joe","bob"]},
        success: function(data) {
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.log(this.props.url, status, err.toString());
        }.bind(this)
});

I am able, however, to make such a request appropriately with httpie (simple http command line client): 但是,我可以通过httpie(简单的http命令行客户端)适当地发出这样的请求:

echo '{"subject":"something", "members":["joe","bob"]}' | http  --auth test:test POST localhost:8000/api/some_page/ --verbose

What might I be doing wrong in the javascript request such that the inputs come into the server differently than expected? 我在javascript请求中可能做错了什么,导致输入到服务器的输入不同于预期?

在调用ajax函数之前尝试对对象进行字符串化

JSON.stringify({subject: "something", members: ["joe","bob"]})

Try this 尝试这个

data: {subject: "something", members: ["joe","bob"]},

Then in backend 然后在后端

request.POST.getlist('members[]')

IF you want to use application/json as contentType .Then try this 如果您想使用application/json作为contentType 。那么尝试一下

data: JSON.stringify({subject: "something", members: ["joe","bob"]}),
contentType: 'application/json; charset=utf-8',

In backend, 在后端,

json.loads(request.body)['members']

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

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