首页 > 解决方案 > 如何使用 jQuery 将存储在变量中的图像文件发送到 php

问题描述

我想使用 jQuery 将图像文件发送到 PHP 文件,首先将图像存储在变量中,然后将其发送以进行处理。php 代码输出如下错误:

未定义索引:第 2 行 C:\xampp\htdocs\edash\admin\checks\a_addQuest.php 中的 img

这是html代码。

<input type="file" name="img" id="img">

这是我的js代码。

$("#submitQuest").click(function() {
    var  dataString;
    var img  = $("#img")[0].files[0];
    dataString   = "img="+img;

    $.ajax({
       type : "POST",
       url  : "../admin/checks/a_addQuest.php",
       data : dataString,
       success: function (result) {
            $("#output").html(result).fadeIn("slow", function () {
            $("#output").fadeOut(3000);
        });
     }
  });
  return false;
});

这是php文件。

<?php
     $img = $_FILES['img']['name'];
     if($img){
           echo "working";
     }
?>

标签: javascriptphpjquery

解决方案


$("#submitQuest").click(function() {
    var data = new FormData();
    data.append('file', $('#img')[0].files[0]);

    $.ajax({
       type : "POST",
       url  : "../admin/checks/a_addQuest.php",
       data : data,
       cache: false,
       contentType: false,
       processData: false,
       success: function (result) {
          $("#output").html(result).fadeIn("slow", function () {
              $("#output").fadeOut(3000);
          });
       }
    });
    return false;
});

推荐阅读