本文实例讲述了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" 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>
内容版权声明:除非注明,否则皆为本站原创文章。