如何从apiUrl获取json数据?需要一些帮助编写函数
changeUrl: function(evt){
this.setState({
value: evt.target.value,
apiUrl: "https://test.holmusk.com/food/search?q=" + evt.target.value
});
},
getJson: function() {
},
最佳答案
您的代码有点混乱,因为当我假设您需要调用该URL来获取Json数据时,很难说出为什么要在setState中设置apiURL。评论者很好地说明了如何使用Redux之类的数据库来建立数据检索架构。但是,如果您只想进行普通的Javascript调用,则可以执行以下操作。很难确定您是否需要组件状态下的Json结果,但是我猜您确实需要这样做,因此我在考虑到这一假设的情况下重新排列了代码。
changeUrl: function(evt){
getJson(evt.target.value);
},
getJson: function(newVal) {
var request = new XMLHttpRequest();
request.open('GET', "https://test.holmusk.com/food/search?q=" + newVal, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
//this callback gets called when the server responds to the ajax call
request.onreadystatechange = function(){
if (request.readyState === 4 && request.status === 200){
var returnedJson = JSON.parse(request.responseText);
//this is where you would want to run setState if you need the returned Json for it.
setState({newJson: returnedJson});
}
else if (request.readyState === 4 && request.status !== 200){
alert('error');
}
};
request.send();
}