donglu2008 2017-06-15 15:34
浏览 40
已采纳

如何使用ajax上传图像

I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. what is wrong with my ajax code. This works when am submitting form with plain text but not with image file.

test.php

<div class="preview_d_p" id="preview_d_p">
<div class="preview">
    <div class="p_preview">
       <div id="p_p_image"><div id="myimage"></div></div>
    </div>
    <div id="lab"> <label for="photo_upload">upload</label></div>
      <form enctype="multipart/form-data">
      <input type="file" id="photo_upload" name="image_upload">
    <input type="submit" value="save" id="insert_img" onclick="return loadimage()">
    </form>
</div></div>


<script>
function loadimage(){
       var image = documentElement('photo_upload').value;



     $.ajax({
         type:'post',
         url:'profile.php',
         data:{
            image:image

         },
         cache:false,
          success: function(html){

          }

     });

       return false;
    }
</script>
  • 写回答

2条回答 默认 最新

  • doudi4621 2019-06-04 09:59
    关注

    I solved this problem using formdata to send my image file to server

    $(document).on("submit","form",function(e){
        e.preventDefault();
    
        var file = $("#product-file-i").val();
        var p = $("#product-upload-f").children("input[name=name]").val();
    
     $.ajax({
                 type:"post",
                 url:"profile.php",
                 data:new FormData(this),
                 contentType:false,
                 processData:false,
                 cache:false,
                 success: function(feedback){
                  alert(feedback);
    
                 },
                 error: function(){
    
                 }
    
              });
    
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi