我正在尝试使用 AJAx 构建一个上传器。我想使用 AJAX 而不是表单和 Iframe,因为我希望默认 CSS 样式与响应一起使用。
问题是,我的 PHP 位于远程服务器上。我正在使用 Shopify,但他们不允许我使用他们的 PHP 服务器,所以我将其放在不同的服务器上。由于某种原因,它不起作用。这是我的代码:
<form action="" id="formContent" method="post" enctype="multipart/form-data" >
<input type="file" name="file" required id="upload">
<button class="submitI" >Upload Image</button>
</form>
<script type="text/javascript">
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "http://myserver.com/upload.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
crossDomain: true,
success: function(){
alert("file successfully submitted");
},
error: function(){
alert("okey");
}
});
});
我得到的只是错误消息。
我正在遵循此回复中概述的代码:https://stackoverflow.com/a/38450277/6442152 https://stackoverflow.com/a/38450277/6442152
我还尝试使用 xmlhttprequest 使用此代码:
$(':file').change(function(){
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
if(file.name.length < 1) {
}
else if(file.size > 100000) {
alert("The file is too big");
}
else {
$(':submit').click(function(){
var formData = new FormData($('*formId*')[0]);
$.ajax({
url: 'script', //server script to process data
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // progressbar
}
return myXhr;
},
// Ajax events
success: completeHandler = function(data) {
/*
* Workaround for Chrome browser // Delete the fake path
*/
if(navigator.userAgent.indexOf('Chrome')) {
var catchFile = $(":file").val().replace(/C:\\fakepath\\/i, '');
}
else {
var catchFile = $(":file").val();
}
var writeFile = $(":file");
writeFile.html(writer(catchFile));
$("*setIdOfImageInHiddenInput*").val(data.logo_id);
},
error: errorHandler = function() {
alert("Something went wrong!");
},
// Form data
data: formData,
// Options to tell jQuery not to process data or worry about the content-type
cache: false,
crossDomain: true,
contentType: false,
processData: false
}, 'json');
});
}});
这也给我带来了错误消息,然后它说 404 文件未找到
我也将此标头添加到我的 PHP 中,但它不起作用:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');