我正在使用jquery ajax和php在onchange事件上上传图像,代码可以正常工作,但是,但是它没有上传图像,在其他页面上显示未定义的索引照片

index.php

<form id="reg" method="POST" enctype="multipart/form-data">
  <div class="form-group">
    <input type="file" name="photo" id="photo" onchange="myfunction(this.form);" >
    <span id="photoid"></span>
  </div>
</form>

<script>
  function myfunction(theForm) {
    var formData = new FormData(this);

    $.ajax({
      type: 'POST',
      url: 'regimg.php',
      data: formData,
      success: function (data) {
        $('#photoid').html(data);
      },
      cache: false,
      contentType: false,
      processData: false
    })
  }
</script>


regimg.php

<?php
  include 'db.php';
  if ($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $photo = $_FILES['photo']['name'];
    $query = mysqli_query($conn,"INSERT INTO img(image) VALUES('$photo')");
    if ($query AND move_uploaded_file($_FILES['photo']['tmp_name'], 'image/'.$photo))
    {
      echo 'Data has been added';
    }
    else
    {
      echo 'data could not be added';
    }
  }
?>


当我单击该文件时,将显示一个错误,即未定义的索引照片。
请帮我解决这个问题

最佳答案

函数中的thiswindow,而不是form元素。将FormData行更改为:

var formData = new FormData(theForm);

09-25 20:53