使用react.js从api函数获取json数据
get json data from api function using react.js
如何从apiUrl获取json数据?需要一些帮助来编写函数
changeUrl: function(evt){
this.setState({
value: evt.target.value,
apiUrl: "https://test.holmusk.com/food/search?q=" + evt.target.value
});
},
getJson: function() {
},
您的代码有点令人困惑,因为很难判断为什么要在setState中设置apiURL,而我认为您需要调用该URL来获取Json数据。评论者提出了一个很好的观点,即使用像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();
}
相关文章:
- 如何使用 Node JS 获取 JSON 嵌套数组值
- 使用Javascript/JQuery获取JSON GET数据
- 在jQuery中获取JSON
- 如何使用jQuery按键搜索和获取json行数据
- 如何使用jquery获取Json的节点
- 通过字符串获取JSON对象
- 通过Azure存储以HTML形式获取JSON文件
- 获取JSON并使用Javascript解析为字符串
- 如何在angular中获取json对象的名称
- 如何使用angular获取json对象的名称
- 如何使用Ajax JQuery.ech()获取JSON值
- 可以't通过从googlemapapi获取json值
- 获取json结果的身份验证问题
- Javascript:获取 JSON 中的值计数
- 按服务获取JSON数据
- 如何使用javascript获取json元素
- 从javascript文件中获取JSON,并使用NodeJS在路由文件中显示
- 如何从给定的代码中获取JSON对象
- 获取 JSON 数据将数组项添加到变量
- 如何从具有动态可观察属性的淘汰对象中获取 JSON 字符串