我开发了一个PHP端点,它发回PHP $ _POST和$ _FILES全局变量的内容。这很完美。代码如下所示。
function debug() {
var_dump($_POST);
var_dump($_FILES);
}
当我使用Postman发送"表格"表单数据两个变量,一个文本,一个文件我得到从API端点返回的预期格式。
array (size=1)
'subject' => string 'some subject' (length=12)
array (size=1)
'uploads' =>
array (size=5)
'name' => string 'up loadme.pdf' (length=12)
'type' => string ' application/pdf' (length=15)
'tmp_name' => string '/tmp/phpIiSqAv' (length=14)
'error' => int 0
'size' => int 12325
然而,当我按下代码按钮时,我将生成的代码放在我的浏览器中:
array (size=2)
'subject' => string 'some subject' (length=12)
'uploads' => string '/home/ken/Documents/uploadme.pdf' (length=32)
array (size=0)
empty
可以看出$ _POST数组包含varable和$ _FILES数组都是空的。
邮递员生成的代码片段是
var form = new FormData();
form.append("subject", "some subject");
form.append("uploads", "/home/ken/Documents/uploadme.pdf");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://localhost/mms/public/CommunicatorEmail/debug",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "4b2b2b5b-dc9a-0e27-3a2b-cb763e816b94"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
所以问题是为什么帖子是邮递员而不是邮递员代码按钮生成的jquery / ajax?
由于
答案 0 :(得分:0)
我花了很多时间使用$ .ajax和代码片段。我尽可能地剥离了“垃圾”,制作了简单的案例并提出了
var fdata = new FormData();
//loop through the files in the upload input
for (let file of $("#upload")[0].files) {
fdata.append("file", file);
}
//append fields from form
fdata.append("subject", "some subject");
$.ajax({
type: 'POST',
url: 'public/CommunicatorEmail/debug',//the full endpoint was unnecessary in my case
data: fdata,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
},
error: function(response){
//do something based on the error
}
});
如果你想在php中将文件和帖子信息发送到端点并使用全局变量,请不要使用代码生成的代码片段使用我在上面创建的代码。
我希望这有助于某人。