前台就是一个表单,这里是用的bootstrop的
<form method="post" > <!-- token验证 --> <!--{{ csrf_field() }}--> <div class="form-group" style="width:30%"> <label for="exampleInputPassword1">昵称</label> <input type="name" id="nickname" name="nickname" class="form-control" id="exampleInputname1" placeholder="用于评论昵称"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email </label> <input style="width:30%" type="email" id="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="用于接收回复消息通知"> <span id="error_massage"></span> </div> <div class="form-group" style="width:60%;"> <label for="name">留言内容</label> <textarea class="form-control" id="content" name="text" rows="3" placeholder="评论内容"></textarea> </div> <button type="submit" class="btn btn-default">Submit</button> </form>
php只简单验证了一个邮箱
public function postMassage(Request $Request) { $email = $Request->email; $messages = $this->article_messages->where('email',$email)->first(); if (!empty($messages)) { return response()->json(['status' => 'ok','code' => 400,'message' => '该邮箱已存在!换一个吧!',]); } }
ajax的请求POst
<script type="text/javascript"> $("form").submit(function(e){ e.preventDefault();//阻止默认提交,表单不写method="post"这个可以不要 console.log(11); var nickname = $('#nickname').val(); var email = $('#email').val(); var content = $('#content').val(); $.ajax({ type: "post", url: "/article/message", dataType:"json", data:{ "nickname":nickname, "email":email, "content":content, "_token":"{{ csrf_token() }}", }, success: function(data) { if (data.code == 400) { console.log(data); document.getElementById('error_massage').innerHTML =data.message; } else { } } }); // $.post("/article/message", { // "nickname":nickname, // "email":email, // "content":content, // "_token":"{{ csrf_token() }}", // }, // function(data){ // console.log(data); // }); }) </script>
最终:
以上这篇Ajax请求PHP后台接口返回信息的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持阿兔在线工具。