jquery使用AJAX完成上传图片文件信息

  • 3,441

jquery使用AJAX完成上传图片文件信息

form表单

<form action="" method="post" class="form-horizontal" id="exampleStandardForm" autocomplete="off" style="width: 50%;">
  <div class="form-group">
    <input type="hidden" name="id" value="{$brand.id}">
    <label class="col-sm-3 control-label">品牌名称</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="name" value="{$brand.name}">
      <span class="err" id="err_name" style="color:#F00; display:none;"></span>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-3 control-label">品牌网址</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="url" value="{$brand.url}">
      <span class="err" id="err_url" style="color:#F00; display:none;"></span>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-3 control-label">所属分类</label>
    <div class="col-sm-9">
      <select name="parent_cat_id" id="parent_id_1" onchange="get_category(this.value,'parent_id_2','0');" aria-controls="dataTableExample" class="form-control select">
        <option value="">请选择分类</option>{foreach name="cat_list" item="v"}
        <option value="{$v['id']}" {if condition="$v['id'] eq $brand['parent_cat_id']" } selected="selected" {/if}>{$v['name']}</option>{/foreach}</select>
      <select name="cat_id" id="parent_id_2" aria-controls="dataTableExample" class="form-control select">
        <option value="0">请选择分类</option></select>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-3 control-label">品牌LOGO</label>
    <div class="col-lg-4 col-sm-6">
      <div class="example-wrap">
        <h4 class="example-title"></h4>
        <div class="example">
          <input type="file" class="form-control" id="input-file-now-custom-1" name="file" data-plugin="dropify" data-default-file="{$brand.logo}"></div>
      </div>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-3 control-label">排序</label>
    <div class="col-sm-9">
      <input type="text" class="form-control" name="sort" value="{$brand.sort}">
      <span class="err" id="err_sort" style="color:#F00; display:none;"></span>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-3 control-label">描述</label>
    <div class="col-sm-9">
      <textarea rows="4" cols="60" name="desc" id="desc" class="form-control">{$brand.desc}</textarea>
      <span class="err" id="err_desc" style="color:#F00; display:none;"></span>
    </div>
  </div>
  <input type="hidden" name="id" value="{$brand.id}">
  <div class="text-right">
    <button type="button" class="btn btn-primary" onClick="verifyForm();" id="">提交</button></div>
</form>

jq-ajax事件

function verifyForm(){
        if(document.getElementById("input-file-now-custom-1").files[0] == undefined){
          var file = '';
        }else{
          var file = document.getElementById("input-file-now-custom-1").files[0];
        }

        $('span.err').show();
        var formData = new FormData();
        formData.append('id', $("input[name=id]").val().trim());//trim  去除两边空白
        formData.append('name', $("input[name=name]").val().trim());
        formData.append('url', $("input[name=url]").val().trim());
        formData.append('parent_cat_id', $("#parent_id_1").val().trim());
        formData.append('cat_id', $("#parent_id_2").val().trim());
        formData.append('file',file);
        formData.append('sort', $("input[name=sort]").val().trim());
        formData.append('desc', $("#desc").val().trim());

        $.ajax({
            type: "POST",
            url: "{:Url('Goods/saveBrand')}",
            data: formData,
            contentType: false,
            processData: false,
            mimeType: "multipart/form-data",
            dataType: "json",
            error: function (e) {
                console.log(e);
                layer.alert("服务器繁忙, 请联系管理员!");
            },
            success: function (data) {
                if (data.status == 1) {
                    layer.msg(data.msg, {icon: 1});
                    location.href = "{:Url('Goods/brandList')}";
                } else {
                    layer.msg(data.msg, {icon: 2});
                    $.each(data.result, function (index, item) {
                        $('#err_' + index).text(item).show();
                    });
                }
            }
        });
    }

PHP后台处理

/**
     * 添加修改编辑  商品品牌
     */
    public  function saveBrand(){
            $id = input('id');
            if(\think\Request::instance()->isPost())
            {


                $data = input('post.');
                $brandVilidate = \think\Loader::validate('Brand');
                if($_FILES['file']){
                  $path = upload();
                  if (preg_match("/[\x7f-\xff]/", $path)) {//判断是否有中文存在,有则是错误信息
                      $return = ['status'=>0,'msg'=>$path,'result'=>$brandVilidate->getError()];
                      $this->ajaxReturn($return);
                    }else{
                      $filelogo = \think\Db::name('brand')->where(['id'=>$id])->find();
                      @unlink(ROOT_PATH.$filelogo['logo']);
                      // if(file_exists(ROOT_PATH.$filelogo['logo'])){
                      //     echo '文件存在,可以删了';
                      //     } else {
                      //     echo '猪,文件不存在,可能路径添错了';
                      //     }
                      // exit;
                      $data['logo'] = '/public/uploads/'.$path;//给logo赋值路径
                    }
                }
                unset($data['file']);
                if($id){
                  if(!$brandVilidate->batch()->scene('edit')->check($data)){
                      $return = ['status'=>0,'msg'=>'操作失败','result'=>$brandVilidate->getError()];
                      $this->ajaxReturn($return);
                  }
                  \think\Db::name("Brand")->where('id',$id)->update($data);
                }else{
                  if(!$brandVilidate->batch()->check($data)){
                      $return = ['status'=>0,'msg'=>'操作失败','result'=>$brandVilidate->getError()];
                      $this->ajaxReturn($return);
                  }
                  \think\Db::name("Brand")->insert($data);
                }
                $this->ajaxReturn(['status'=>1,'msg'=>'操作成功','result'=>'']);
            }
           $cat_list = \think\Db::name('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
           $this->assign('cat_list',$cat_list);
           $brand = \think\Db::name("Brand")->where('id',$id)->find();
           $this->assign('brand',$brand);
           return $this->fetch('_brand');
    }

 

weinxin
我的微信
这是我的微信扫一扫
开拓者博主
  • 本文由 发表于 2018年4月30日19:59:54
  • 转载请务必保留本文链接:https://www.150643.com/503.html
匿名

发表评论

匿名网友 填写信息