简体   繁体   English

无法从公共API获取响应(在React.js中)

[英]Can't get a response from a public API (in React.js)

I am new to React.js and I have been working on a simple form. 我是React.js的新手,我一直在研究一个简单的表格。 I send the form data using ajax but I can't get a response. 我使用ajax发送表单数据但我无法得到响应。 When I run it, it gives me readystate is not 4 , on the console, which I have put there for debugging. 当我运行它时,它给了我readystate不是4 ,在控制台上,我已经把它放在那里进行调试。 I don't know where am I going wrong. 我不知道我哪里错了。 Here is my code: 这是我的代码:

import React from 'react'
import ReactDOM from 'react-dom'
import { Field, Form, actions } from 'react-redux-form'
import classes from './SignUp.scss'


export class SignUp extends React.Component {

    constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(user) {

    const { dispatch } = this.props;

    const somePromise = new Promise((resolve) => {

         console.log(user);            
         this.setState({}, this.sendFormData);

    });

    dispatch(actions.submit('user', somePromise));    

  }    

  sendFormData(){


    var formData = {
      fn: ReactDOM.findDOMNode(this.refs.fn).value,
      ln: ReactDOM.findDOMNode(this.refs.ln).value,
      city: ReactDOM.findDOMNode(this.refs.city).value,
      //rlc: ReactDOM.findDOMNode(this.refs.rlc).value
    };

    //for check boxes
    formData.yes = this.getSelected('yes');
    formData.no = this.getSelected('no');

    // Send the form data.
    var xmlhttp = new XMLHttpRequest();
    var _this = this;
    xmlhttp.open('POST','http://jsonplaceholder.typicode.com/users',true);
    xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {

        var response = JSON.parse(xmlhttp.responseText);
        if (xmlhttp.status == 200 && response.status == 'OK') {
          console.log('success');              
        }

        else{
          console.log('failure')              
        }

        console.log('readystate is 4')
      }
      else {console.log('readystate is not 4')}
    };


    xmlhttp.send(this.requestBuildQueryString(formData));
  }


  requestBuildQueryString(params){

    var queryString = [];
    for(var property in params)
      if (params.hasOwnProperty(property)) {
        queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(params[property]));
      }

    return queryString.join('&');

  }

  getSelected(fieldName) {
    var i;
    var fields = document.getElementsByName(fieldName);
    var selectedFields = [];
    for (i = 0; i < fields.length; i++) {
      if (fields[i].checked === true) {
        selectedFields.push(fields[i].value);
      }
    }
    return selectedFields.join(', ');

  }

  render() {


    let { user } = this.props;

    return (

      <Form model="user" onSubmit = {this.handleSubmit}>

        <div>
          <Field model="user.fname">
          <label>First Name: </label>
          <input type="text" placeholder= "First Name" ref="fn"/>
          </Field>
        </div>


        <div>
          <Field model="user.lname">
          <label>Last Name: </label>
          <input type="text" placeholder="Last Name" ref="ln"/>
          </Field>
        </div>

        <div>
          <Field model="user.live">
          <label>Where do you live? </label>
          <input type="text" placeholder="Your City" ref="city"/>
          </Field>
        </div>

        <div>
          <Field model="user.relocate" ref="rlc">
          <label>Are you willing to relocate?</label>
          <label>
          <input type="radio" value="Yes" ref="yes" checked={user.relocate.value === 'Yes'}/> Yes
          </label>

          <label>
          <input type="radio" value="No" ref="no" checked={user.relocate.value === 'No'}/> No
          </label>
          </Field>
        </div>

        <div>
          <button type="submit">
          Lets go, {user.fname} {user.lname}!
          </button>
        </div>
      </Form>
  )
  }
}

SignUp.propTypes = {
    dispatch: React.PropTypes.func.isRequired,
    user: React.PropTypes.shape({
    fname: React.PropTypes.string.isRequired,
    lname: React.PropTypes.string.isRequired,
    live: React.PropTypes.string.isRequired,
    relocate: React.PropTypes.string.isRequired,

  }).isRequired,
};

export default SignUp;

And this is the output on my console: 这是我的控制台上的输出:

console 安慰

You must do it in the correct order: 您必须按正确的顺序执行此操作:

  1. construct 构造
  2. open 打开
  3. set handler 设置处理程序
  4. send 发送

you are setting handler before opening 你在打开前设置处理程序

Also, 也,

" Note: The onreadystatechange event is triggered five times (0-4), one time for each change in readyState. " 注意:onreadystatechange事件被触发五次(0-4),对于readyState中的每次更改都会触发一次。

So if you see 'readystate is not 4' a few times before eventually 'readystate is 4', it's ok 因此,如果你在'readystate is 4'之前看到'readystate is not 4'几次,那就没关系了

EDIT: try replacing, if (xmlhttp.status == 200 && response.status == 'OK') with if (xmlhttp.status == 201). 编辑:尝试使用if(xmlhttp.status == 201)替换if(xmlhttp.status == 200 && response.status =='OK')。 Your host returns status code 201 您的主机返回状态码201

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

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