[英]RESTful request in ajax and react
美好的一天,我試圖在反應中消耗Web服務,但是我在ajax函數方面遇到問題,我不確定我的代碼是否在工作:
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)
});
但是我沒有任何警報,當我單擊按鈕僅重新呈現表單時,函數句柄提交工作正常,我嘗試將confirm()放在// tag注釋所在的空間中,並彈出確認,但是警報沒有,我認為我在功能或某些方面有錯誤,謝謝您的幫助。
我沒有運行腳本,而是看着它,我想問題可能出在您的bind(this)
對我來說this.setState
應該是一個錯誤“ 不是函數 ”,因為this
不是反應對象。 要獲取警報,請嘗試將警報設置為第一狀態。
可以肯定的是,請查看您的瀏覽器控制台。
看起來大部分時間都在工作。 我將其放入一個JSBin中,似乎沒有什么異常。
http://jsbin.com/rulaguxote/1/edit?html,js,輸出
我使您的JSX基本保持不變,並在組件中添加了一些內容來幫助您可視化其狀態。 單擊按鈕發送偽造的ajax請求。 根據狀態,它將發送回200或400的HTTP狀態(成功或失敗)。 這樣,您可以看到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");
}
});
如果您有任何疑問,請告訴我。
經過大量研究,我發現我的真正問題出在同一來源策略上,現在在項目的localhost版本中可以正常工作,謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.