RESTful request in ajax and react

时间:2015-07-28 16:03:48

标签: javascript jquery ajax reactjs

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.

3 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

看起来它大部分都在工作。我把它扔进了一个JSBin,似乎没有任何异常。

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

我保持你的JSX大致相同,并在组件中添加了一些东西来帮助你可视化它的状态。单击按钮发送虚假的ajax请求。根据状态,它将发回HTTP状态200或400(成功或失败)。这样,您就可以了解success()error()函数的行为方式。

需要注意的另一件事是:如果您担心自己的.bind(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");
    }
});

如果您有任何问题,请与我们联系。

答案 2 :(得分:0)

做了一些广泛的研究,我发现我的真正问题是相同的原始政策,现在我在项目的localhost版本中工作正常,谢谢。