使用 React Native 将数组发送到服务器以获取一些数据

K.S*_*ith 3 arrays api http-post react-native fetch-api

我正在尝试使用给定的数据从服务器获取数据。我正在使用以下代码:

    const details = {
      'function': 'getUsers',
    };
    const formBody = 
    Object.keys(details).map(key=>encodeURIComponent(key)+
    '='+encodeURIComponent(details[key])).join('&');
    console.log(formBody);
    fetch(url, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'XPIDER_SID=' + this.props.text
      },
      body: formBody
      }).then((response) => response.json())
        .then((responseJson) => {
          if (responseJson.status === 'okay') {
            this.setState({ users: responseJson.users });
          } else {
             this.setState({ error: responseJson.error });
          }
      })
Run Code Online (Sandbox Code Playgroud)

直到现在它都很好用。现在我必须发送一个数据数组,但是当我在细节常量中写入一个数组时,由于 formBody,服务器不接受该数组。在formBody中,整个请求都是字符串,所以数组转为字符串。我怎样才能用这个发送一个数组?或者你们知道其他选择吗?谢谢你 !

lin*_*new 5

像这样将您的数组作为 JSON 发送:

body: JSON.stringify(your_array)
Run Code Online (Sandbox Code Playgroud)

然后在服务器上反序列化

  • 谢谢你的回答。但我不能发送 JSON,因为格式必须是 x-www-form-urlencoded (2认同)