我想通過$.post
在ReactJS發佈數據,並作出從像PUBLISHER_ID一些標準數據庫中檢索數據的API使用它。 我所試圖做的是從一個特殊的類稱爲用戶採取PUBLISHER_ID,然後通過我的應用程序做出反應張貼到API文件。我偶然發現了這是通過形式發送時數據發送到服務器,通常情況下,一個onSave
功能我只能用$。員額問題。我完全知道這是如何工作,但我的問題是:
有沒有辦法發送數據$.post
或其他什麼都正確,當渲染過程開始?
我一直在使用componentWillMount
爲此事嘗試,但我偶然發現了另一個問題。我注意到,通常,爲了使$.post
正常工作,必須觸發事件。
我應該使用什麼樣的事件做我想要什麼?
代碼
對於$.get
方法我使用的工作只是正常的情況如下:
componentDidMount: function()
{
this.serverRequest = $.get("get_user_id.php", function (publisher_id)
{
this.setState(
{
publisher_id: JSON.parse(publisher_id)
});
}.bind(this));
}
我需要爲我的API來的工作做的是檢索數據的情況發生之後,發佈publisher_id
到read.php
,文件RESPONSABLE從數據庫中檢索只有特定的數據。
編輯:
我試圖做的是以下幾點:
componentDidMount: function()
{ //previous code
this.serverRequest = $.post("read_all_products.php", {
publisher_id: this.state.publisher_id,
})
}
正如前面提到的,完全檢索數據,因爲當後來在渲染功能,試圖用{這顯示它的工作原理.state.publisher_id}它將正確顯示。 什麼是不工作的數據的職位。我可能沒有完全意識到我應該怎麼做,因爲我再次試圖在頁面加載時發送它。
EDIT2: 我也試過從主組件傳遞publisher_id作爲prop,所以$ .get方法現在在那裏發生。然後,我做了以下內容:
componentWillMount: function() {
this.serverRequest = $.post("read_all_products.php", {
publisher_id: this.props.publisher_id,
});
},
componentDidMount: function() {
this.serverRequest = $.get("read_all_products.php", function (products) {
this.setState({
products: JSON.parse(products)
});
}.bind(this));
}
那沒有工作,我嘗試使用的onSave功能發送假形式:
onSave: function (e) {
$.post("read_all_products.php", {
publisher_id: this.props.publisher_id,
});
e.preventDefault();
}// used after this in the render method on a form with a button, both
//have onSubmit and onClick set to {this.onSave}
我仍然期待着別人的幫助。我幾乎陷入了困境,並且在過去幾天一直如此。我需要得到這個工作,否則我需要改變身份驗證或繼續堅持這一點。
問題是:如何在React中使用$ .post將一個名爲publisher_id的道具發送到頁面加載的我的.php api文件中,甚至可以說,如果其他任何東西都不可行,它使用一個空的表單發送數據,在componentDidMount之前按下它自己一次,可能在componentWillMount中?
一種代碼解決方案上面不存在:
對於一個正常的AJAX文章你不必觸發一個事件。你在代碼中完成它的方式,你必須,當你將它分配給'this.serverRequest'時。但是,爲什麼你使用'$ .get'作爲POST? – putvande
我正在使用$ .get從其類中檢索publisher_id,然後將其設置爲componentDidMount中的狀態。我試圖使用$ .post將publisher_id發送到另一個php文件,然後使用條件「... WHERE p.publisher_id =」從數據庫中選擇一個產品數組。 this-> publisher_id。 「...」 –