У меня есть проект 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'));
Я использовал оба fetch (), как вы можете видеть вмой код (прокомментировал) jquery ajax, но оба запускают функцию ошибки.
console.log(errorThrown.toString());//show nothing
console.log(textStatus)// error