我有一个Reactjs项目,我正在使用ajax从我的php API中获取数据。 状态为200,响应为json,但会触发错误:
import React from 'react';
import ReactDOM from 'react-dom';
class User extends React.Component{
constructor(){
super();
this.state={username:'someone'}
}
click_btn=()=> {
/* fetch("http://localhost/react/api/insert.php")
.then(res => res.json())
.then(
(result) => {
this.setState({
username: result.name
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
username:'error'
});
}
)*/
$.ajax({
url:"http://localhost/react/api/insert.php",
type:'post',
dataType:'json',
success:function (data, status,x) {
alert(data.name)
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
}
})
}
render() {
return(
<div><h1 id={'name'}>{this.state.username}</h1>
<button type='button' onClick={this.click_btn}>show</button>
</div>
)
}
}
ReactDOM.render(<User/>,document.getElementById('root1'));
insert.php文件:
<?php
echo json_encode(array('name'=>'Jack'));
正如我在代码中(注释过)jquery ajax所看到的,我已经使用了两个fetch(),但是都触发了错误功能。
console.log(errorThrown.toString());//show nothing
console.log(textStatus)// error
答案 0 :(得分:0)
解决了! 我将标头添加到了我的PHP文件中:
<?php
header('Access-Control-Allow-Origin: *');
echo json_encode(array('name'=>'Jack'));