问题
I'm trying to invoke a PHP script to upload a file via Ajax.
var fd = new FormData();
fd.append('file', file);
console.log(file);
var xhr = $.ajax({
url: 'https://www.mywebsite.com/it/file/upload/',
type: 'POST',
dataType: 'json',
data: fd,
cache: false,
contentType: false,
processData: false,
success: function(result, message, xhr)
{
console.log(result);
}
});
For the moment, the PHP script simply displays the received file data
header('Content-Type: application/json');
echo json_encode($_FILES['file']);
die();
The "file" object passed to ajax data is the following
File {errors: 0, name: "wedding.jpg", lastModified: 1500572565619, lastModifiedDate: Thu Jul 20 2017 19:42:45 GMT+0200 (ora legale Europa occidentale), webkitRelativePath: ""…}
But when ajax call is invoked, in the inspect window I get the following error
jquery.min.js:4 POST https://www.mywebsite.com/it/file/upload/ 404 (Not Found)
It sounds very strange, since when I directly browse the script path, it doesn't give any 404 response.
If I comment the "contentType" parameter the error disappears, but the received response from PHP script is null
.
What am I missing?
回答1:
You need to specify the content type to what is expected. As you mentioned in your post, the php
file has
header('Content-Type: application/json');
So, try changing it
contentType: false,
to
contentType: "application/json; charset=utf-8",
来源:https://stackoverflow.com/questions/45257368/error-404-not-found-in-ajax-call-with-file-inside-formdata