duanlinpi0265 2017-07-05 10:06
浏览 176

使用ajax和JavaScript函数上传文件[重复]

This question already has an answer here:

Need a big favor! I'm trying to send uploaded file using JavaScript & Ajax, however not getting any success.

I want that when I upload the file, it will call the function myFunction(), and send the file to the PHP path(ajax.php) I've set.

Below is the code I've so far.

<script>
   function myFunction() {
      var x = document.getElementById("up");
      $.ajax({
         type: 'GET',
         url: 'ajax.php',
         data: {},
         beforeSend: function() {},
         success: function(data) {
            alert(data);
         }
      });
   }
</script>
<input type="file" name="images" id="up" onchange="myFunction()" />
</div>
  • 写回答

4条回答 默认 最新

  • doukang5966907 2017-07-05 10:12
    关注

    Uploading files with Jquery and Ajax is a little tricky, but it is something that is already fairly well documented. A quick google search returns a fairly good example of this https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

    The most important part is obtaining the formdata. Javascript can grab the file elements and build a FormData object from it. From the example above

    $('input[type=file]').on('change', prepareUpload);
    function prepareUpload(event)
    {
      files = event.target.files;
    }
    

    You can then build the form object and use that as the data component of your ajax request.

    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况