发送输入文件和其他字符串在PHP错误

时间:2018-07-10 10:21:12

标签: javascript php jquery ajax

我想通过ajax发送输入文件和一些字符串,但是我不能发送该文件,因为它不必进行处理(因此我应该使用processData:false),但是如果我使用它,我传递的每个字符串结果未索引

JS脚本:

var Name = document.getElementById("Name").value;
    var Surname = document.getElementById("Surname").value;
    var Residence = document.getElementById("Residence").value;
    var Email = document.getElementById("Email").value;
    var Phone = document.getElementById("Phone").value;
    var JCurriculum = document.getElementById("Curriculum").files[0];
    var Curriculum = new FormData();
    Curriculum.append("Curriculum", JCurriculum);
    $.ajax({
        method: 'POST',
        url: "scripts/register.php",
        data: {
            Name: Name,
            Surname: Surname,
            Residence: Residence,
            Email: Email,
            Phone: Phone,
            Curriculum: Curriculum
        },            
        success: function (Curriculum) {
            alert('Success');
        }
    });

PHP脚本:

$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Surname = $_POST['Surname'];
$Residence = $_POST['Residence'];
$Phone = $_POST['Phone'];
$Curriculum = $_POST['Curriculum'];

$Name = filter_var($Name, FILTER_SANITIZE_STRING);
$Surname = filter_var($Surname, FILTER_SANITIZE_STRING);
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
$Residence = filter_var($Residence, FILTER_SANITIZE_STRING);;
$Phone = filter_var($Phone, FILTER_SANITIZE_STRING);;

如果我将processData:false放在success:之前,则出现此错误Undefined index

1 个答案:

答案 0 :(得分:1)

您发送的数据不正确。无需将FormData对象与经过表单编码的数据一起序列化,您需要将所有信息(输入值和文件)append()放入FormData对象,然后仅发送。

您还需要将contentTypeprocessData属性都设置为false。试试这个:

var formData = new FormData();
formData.append('Name', $('#Name').val());
formData.append('Surname', $('#Surname').val());
formData.append('Residence', $('#Residence').val());
formData.append('Email', $('#Email').val());
formData.append('Phone', $('#Phone').val());
formData.append('Curriculum', $('#Curriculum')[0].files[0]);

$.ajax({
  method: 'POST',
  url: "scripts/register.php",
  data: formData,
  processData: false,
  contentType: false,
  success: function(Curriculum) {
    alert('Success');
  }
});

还要注意,如果要在请求中发送的所有信息都包含在单个<form />元素内,则可以通过向对象构造函数提供对form元素的引用来简化FormData的创建:

var formData = new FormData($('#yourForm')[0]);