thinkPHP form表單提交
阿新 • • 發佈:2018-12-22
<body> <form autocomplete="off" id="myform"> <input type="text" name="name" value=""/> <input type="text" name="phone" /> <div onclick="ajaxPost()" >11</div> </form> </body> <script> function ajaxPost(){ var formData = $("#myform").serialize(); //serialize() 方法通過序列化表單值,建立 URL 編碼文字字串,這個是jquery提供的方法 console.log(formData) $.ajax({ method:"post", dataType:"json", url:"{:url('index')}", data:formData,//這裡data傳遞過去的是序列化以後的字串 success:function(data){ console.log(data) } }); } </script>
<?php namespace app\index\controller; use think\Controller; use think\Request; class Index extends Controller { public function index() { if (request()->isPost()) { var_dump(input(''));die第一次就捐出去了; $data['name'] = input('name'); $data['phone'] = input('phone'); if(empty($data['name'])){return array('info' => '不能為空!', 'status' => -1);} if(empty($data['phone'])){return array('info' => '不能為空!', 'status' => -1);} if(is_string($data['phone'])){return array('info' => '不能為空!', 'status' => -1);} $res = db('index')->insert($data); if ($res) { return array('info' => '新增成功!', 'status' => 1, 'target' => 'back'); } else { return array('info' => '新增失敗!', 'status' => -1); } }else{ return $this->fetch(); } // return '28822'; } public function test() { return '333'; } }