![](/img/trans.png)
[英]xhr.upload.addEventListener load has empty xhr.responseText
[英]ajax xhr.upload.addEventListener not working for cross domain call
我正在尝试通过jquery ajax调用从我的网站创建视频上传进度条到后端服务,该服务位于同一个域,但是不同的端口
https://mywebsite.com/upload呼叫https://mywebsite.com:3000/api/video/upload
这是我的ajax脚本:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
}
}, false);
return xhr;
},
url: "https://mywebsite.com:3000/api/video/upload",
data: dataForm,
cache: false,
contentType: false,
processData: false,
crossDomain: true,
type: 'POST'
});
调用这个ajax,我的POST请求总是变成OPTIONS
OPTIONS https://mywebsite:3000/api/video/upload Invalid HTTP status code 404
当我删除xhr函数时,ajax脚本工作正常。 我能够上传一个视频,但没有进度监听器。
我的后端是在node.js上构建的。 在此先感谢任何帮助。
我发现我的服务器不支持OPTIONS请求,所以我在node.js文件中添加它
app.options('*', function(req, res, next){
res.send(200);
});
它运作良好:)
当发送GET,POST方法跨域时,OPTIONS方法首先发送“预检”请求。
看起来你得到404 Not Found响应。 通过允许发送OPTIONS方法请求,确保您的请求目标URI返回诸如200 OK之类的内容。
嗯尝试这样的事情:(这是jquery 1.11.x和php文件上传解析器就在html文件旁边)
<script type=“text/javascript”>
function uploadProgressHandler(event)
{
$("#loaded_n_total").html("Uploaded "+event.loaded+" bytes of "+event.total);
var percent = (event.loaded / event.total) * 100;
var progress = Math.round(percent);
$("#uploadProgressBar").html(progress + " percent na ang progress");
$("#uploadProgressBar").css("width", progress + "%");
$("#status").html(progress +"% uploaded... please wait");
}
function loadHandler(event)
{
$("#status").html(event.target.responseText);
$("#uploadProgressBar").css("width", "0%");
}
function errorHandler(event){
$("#status").html("Upload Failed");
}
function abortHandler(event){
$("#status").html("Upload Aborted");
}
$("#uploadFile").click(function(event)
{
event.preventDefault();
var file = $("#fileUpload")[0].files[0];
var formData = new FormData();
formData.append("file1", file);
$.ajax({url: 'http://testarea.local/UploadWithProgressBar1/file_upload_parser.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress",
uploadProgressHandler,
false
);
xhr.addEventListener("load", loadHandler, false);
xhr.addEventListener("error", errorHandler, false);
xhr.addEventListener("abort", abortHandler, false);
return xhr;
}
}
);
}
);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.