本文实例讲述了thinkphp5 + ajax 使用formdata提交数据(包括文件上传) 后台返回json。分享给大家供大家参考,具体如下:
知识点总结
1.json格式标准
{ 'key':"value" } {"state":"1","msg":"\u7b80\u5386\u6295\u9012\u6210\u529f\uff01"}
前端jquery ajax提交formdata
$.ajax({ })
formdata 获取表单数据 包括文件上传
HTML
<form class="am-form" id="recruitinfo"> <div class="col-lg6 col-md-6 col-xs-12 m1rem"> <label>姓名</label> <input type="text" name="post[name]" id="name" required > </div> <div class="col-lg6 col-md-6 col-xs-12 m1rem"> <label>手机号</label> <input type="text" name="post[iphone]" id="iphone" required> </div> <div class="col-lg10 col-md-10 col-xs-12 m2rem"> <label>附件简历:(您的详细信息请都写在简历上,只接受word文档)</label> <div class="am-form-group am-form-file"> <button type="button" class="am-btn am-btn-danger am-btn-sm"> <i class="am-icon-cloud-upload"></i> 选择要上传的简历</button> <input id="doc-form-file" type="file" name="doc" > </div> <div id="file-list"></div> <script> $(function() { $('#doc-form-file').on('change', function() { var fileNames = ''; $.each(this.files, function() { fileNames += '<span class="am-badge">' + this.name + '</span> '; }); $('#file-list').html(fileNames); }); }); </script> <input type="hidden" name="post[jobname]" id="jobname" value="{$data.job}"> <input type="hidden" name="post[jobnameid]" id="jobnameid" value="{$data.id}"> </div> <div class="col-lg-6 col-md-6 col-xs-12"> <button type="submit" class="am-btn am-btn-primary" onclick="submitform()">提交</button> <a href="javascript:window.history.back(-1);" rel="external nofollow" rel="external nofollow" class="am-btn am-btn-default">返回</a> </div> </form>
JS
<script type="text/javascript"> function submitform() { event.preventDefault(); var form =document.getElementById('recruitinfo'), formdata = new FormData(form); var url = '{:url("recruitinfo/postfrom")}'; $.ajax({ url:url, type:'post', data:formdata, dataType:'json', processData:false, contentType:false, success:function (res) { console.log('请求成功!') console.log(res) }, error:function (XMLHttpRequest, textStatus, errorThrown) { console.log('出错啦!') console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }) } </script>
php json_encode()函数转成json
$callbackinfo = array( 'state' => '1', 'msg' => '简历投递成功!', ); $jsondata =json_encode($callbackinfo); echo $jsondata;
问题
1.前端SyntaxError: Unexpected token < in JSON at position 0 报错
报错原因
使用的thinkphp5
没想到是因为使用了dump()函数 var_dump 这些最后echo出来的不正确导致的,还要要按标准格式来啊
解决方法
去掉dump相似的函数
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题