gpt4 book ai didi

javascript - 在 PHP 错误中发送带有其他字符串的输入文件

转载 作者:行者123 更新时间:2023-11-30 20:22:56 24 4
gpt4 key购买 nike

我想通过 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

最佳答案

您发送的数据不正确。您需要 append(),而不是连同表单 urlencoded 数据一起序列化 FormData 对象。所有信息(输入值和文件)到 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 /> 中元素,那么您可以通过向对象构造函数提供对表单元素的引用来简化 FormData 的创建:

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

关于javascript - 在 PHP 错误中发送带有其他字符串的输入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51262765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com