1、后台接收数据时,判断isAjax()始终未false
解决:这是因为axios 请求头中没有带 X-Requested-With 这个参数

2、post请求正常了,但是后台接收到的数据始终是null,用$_POST与param都没用
这是因为content-type 为 "application/json" 的数据 php 是不能直接识别的,所以导致 $_POST 数组为空。
解决:
下面给一个完整的例子,注册账号的例子
<!DOCTYPE html>
<html>
<head>
<title>注册</title>
<link href="{$Think.config.static}/admin/css/aui.css" rel="stylesheet">
</head>
<body>
<div id="app">
<div class="aui-content aui-margin-b-15">
<ul class="aui-list aui-form-list">
<li class="aui-list-header">用户注册</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label">
用户名:
</div>
<div class="aui-list-item-input">
<input type="text" placeholder="Name" v-model='name'>
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label">
密码:
</div>
<div class="aui-list-item-input">
<input type="password" placeholder="Password" v-model="pwd">
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner">
<div class="aui-list-item-label">
密码确认:
</div>
<div class="aui-list-item-input">
<input type="password" placeholder="Password" v-model="pwd2">
</div>
</div>
</li>
<li class="aui-list-item">
<div class="aui-list-item-inner aui-list-item-center aui-list-item-btn">
<div class="aui-btn aui-btn-info aui-margin-r-5" v-on:click="checkpwd()">注册</div>
<div class="aui-btn aui-btn-danger aui-margin-l-5" v-on:click="rewrite()">取消</div>
</div>
</li>
</ul>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="{$Think.config.static}/admin/js/vue.js"></script>
<script type="text/javascript" src="{$Think.config.static}/admin/js/axios.min.js"></script>
<script>
var vm=new Vue({
el:'#app',
data:{
name:'',
pwd:'',
pwd2:''
},
methods:{
checkpwd:function(){
if(this.pwd!=''&&this.pwd2!=''&&this.name!=''){
if(this.pwd==this.pwd2){
this.register(this.name,this.pwd);
}else{
alert('两次密码不一致!');
}
}else{
alert('请输入注册数据!');
}
},
rewrite:function(){
this.name='';
this.pwd='';
this.pwd2='';
},
register:function(name,pwd){
axios({
method: 'post',
url: 'http://127.0.0.1/restudy/public/index.php/admin/index/register',
headers:{"Content-Type":'application/x-www-form-urlencoded;charset=UTF-8','X-Requested-With': 'XMLHttpRequest'},
data:{
username:name,
pwd:pwd
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
});
</script>
public function register()
{
if(request()->isAjax()){
$post = json_decode(file_get_contents("php://input"), true);
$username = $post['username'];
$password = $post['pwd'];
return json(['username'=>$username,'pwd'=>$password]);
}
return $this->fetch();
}
axios跨域的问题之前的文章有记录,暂时算是解决问题了,不知道还有没有其他的坑,有知道的拜托告诉一下
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!