【问题标题】:Uploading an image with php/ajax is refreshing the page使用 php/ajax 上传图片正在刷新页面
【发布时间】:2020-04-25 22:33:20
【问题描述】:

脚本运行良好,我正在使用formData()通过ajax 上传图像,并且它被正确上传到文件夹,但我不明白为什么我的页面在move_uploaded_file() 获取后被刷新在 php 脚本中调用。
这是完整的代码:

index.html

<label>Add picture?</label>
<input type='file' accept='.png,.gif,.jpg' onchange='upload_img(this)'>

script.js

function upload_img(e) {
  let file = e.files[0];
  let formData = new FormData();
  formData.append('file', file);

  let xhr = new XMLHttpRequest();
  xhr.onload = function () {
    // I want to show a message here but the page is being refreshed
    document.getElementById('ajax_result').innerHTML = xhr.responseText;
  }
  xhr.open("POST", "upload_img.php", true);
  xhr.send(formData);
}

upload_img.php

<?php
  if (!empty($_FILES['file'])) {
    var_dump($_FILES['file']);
    $path = "../img_uploads/";
    $path = $path . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
      echo "The file " .  basename($_FILES['file']['name']) . " has been uploaded";
    }
  }

编辑:
出于测试目的,我删除了页面中的所有表单,问题仍然存在。

【问题讨论】:

  • 你没有提交按钮或表单标签或类似的东西?
  • @delboy1978uk 我在页面中有一个表单,但是这个输入在它之外。
  • 你可能在表单标签中有form action=""
  • 我想阻止move_uploaded_file() 实际提交任何内容。有什么方法可以做到吗?

标签: javascript php ajax file-upload form-data


【解决方案1】:

也许先尝试 xfr.open 然后 xfr.onload

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2018-05-19
    • 1970-01-01
    • 2010-09-24
    • 2019-03-07
    相关资源
    最近更新 更多