简体   繁体   中英

RESTful request in ajax and react

good day, im trying to consume a web service in react, but im having problems with the ajax function, i'm not sure if is working my code is this:

prox= {"email":email, "password": password};
//tag comment
$.ajax({
  type: 'POST',
  url: (web service url),
  data: JSON.stringify(prox),
  contentType: "application/json; charset=utf-8",
  crossDomain: true,
  dataType: 'json',   
  success: function(data) {
    this.setState({success: true, result: data});
    alert("success");
    this.setState({prueba: 'success'});
  }.bind(this),
  error: function() {
    this.setState({failure: true});
    alert("failure");
    this.setState({prueba: 'failure'});
  }.bind(this)
});

but i dont have any alert, when i click the button only re-render the form, the function handdle submit works, i try it putting a confirm() in the space where the //tag comment is and the confirm pop up, but the alerts dont, i think that i have an error in the function or something, thank's for the help.

I didn't run the script but just looking at it I imagine the problem could be your bind(this)

this.setState to me should be an error “ is not a function ” as this is not the react object. To get an alert try placing the alert as the first state.

To be sure just look at your browser console.

It looks like its working for the most part. I threw it into a JSBin and nothing seems to be out of the ordinary.

http://jsbin.com/rulaguxote/1/edit?html,js,output

I kept your JSX mostly the same, and added a few things in the component to help you visualize its state. Click the button to send a fake ajax request. Depending on the state, it will either send back an HTTP status of 200 or 400 (success or failure). This way, you can see how the success() and error() functions behave.

Another thing to note: If you are concerned that your .bind(this) is the reason your code is not working, you can specify the context like this:

$.ajax({
    type        : 'POST',
    url         : '/test',
    data        : JSON.stringify(prox),
    contentType : "application/json; charset=utf-8",
    context     : this, //use this instead of .bind
    success     : function (data) {
        this.setState({success : true, failure : false});
        alert("success");
    },
    error       : function () {
        this.setState({failure : true, success : false});
        alert("failure");
    }
});

Let me know if you have any questions.

经过大量研究,我发现我的真正问题出在同一来源策略上,现在在项目的localhost版本中可以正常工作,谢谢。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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