XMLHttpRequest - Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22362032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:10:34  来源:igfitidea点击:

XMLHttpRequest - Laravel

javascriptphpajaxlaravel

提问by cch

I am uploading a file with laravel and using ajax request to create the progress bar for it. This is how the form action routes to the controller:

我正在使用 laravel 上传文件并使用 ajax 请求为其创建进度条。这是表单操作路由到控制器的方式:

<form action="{{ URL::route('upload-file-form-post') }}" method="POST" enctype="multipart/form-data">
.
.
</form>

ajax:

阿贾克斯:

function _(el) {
    return document.getElementById(el);
}

function uploadfile() {
  var file = _("file").files[0];
  // dev
  alert(file.name+" | "+file.size+ " | "+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.open("POST", "here_is_where_the_url_needs_to_go");
  ajax.send(formdata);
}

function progressHandler(event) {
   _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + "bytes of "+ event.total;
   var percent = (event.loaded / event.total) * 100;
   _("progressBar").value = Math.round(percent);
   _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0;
} 

is there a way to send this {{ URL::route('upload-file-form-post') }}to the ajax request?

有没有办法将它发送 {{ URL::route('upload-file-form-post') }}到ajax请求?

in my routes file the above is referenced as:

在我的路由文件中,上述内容被引用为:

Route::post('/asset/upload-file', array(
    'as'  => 'upload-file-form-post',
    'uses' => 'AssetController@postUploadCreate'
));

回答by Rahil Wazir

Simply use JavaScript to get the form action attribute

只需使用 JavaScript 即可获取表单操作属性

//Whatever your action value
var action = document.formName.getAttribute('action');

First:

第一的:

Don't mix onclickevent on submit button, clicking submit button actually process the form itself. Its better to bind submit events to forms instead of binding click events on submit button.

不要onclick在提交按钮上混合事件,单击提交按钮实际上会处理表单本身。最好将提交事件绑定到表单而不是在提交按钮上绑定点击事件。

By giving a nameattribute to your form like name="my_form", you can add submit event handler to your form.

通过name为您的表单提供一个属性,例如name="my_form",您可以将提交事件处理程序添加到您的表单中。

Like this:

像这样:

document.my_form.addEventListener('submit', function(e) {
    e.preventDefault();

    var actionURL = this.action; // will get the form action url
    uploadfile(actionURL); // your upload event with request url
});

Your function uploadfile(..)will accept a parameter called URL. Which will be passed to ajax.open(..)method

您的函数uploadfile(..)将接受一个名为 URL 的参数。哪个将传递给ajax.open(..)方法

Modified:

修改的:

// -----------------!!!! pass parameter for url
function uploadfile(url) {
  var file = _("file").files[0];
  // dev
  alert(file.name+" | "+file.size+ " | "+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.open("POST", url); // your url will pass to open method
  ajax.send(formdata);
}

Edited:

编辑:

To fix Laravel Mismatch token issue (Referrence):

修复 Laravel Mismatch 令牌问题(参考)

Add below <meta >tag within your <head>tag of your current form view file.

<meta ><head>当前表单视图文件的标签中添加以下标签。

<meta name="csrf-token" content="<?php echo csrf_token() ?>">

Or use blade

或者用刀片

<meta name="csrf-token" content="{{{ csrf_token() }}}">

Now within your uploadfile(...)function add this snippet:

现在在你的uploadfile(...)函数中添加这个片段:

var metas = document.getElementsByTagName('meta'); 

for (i=0; i<metas.length; i++) { 
    if (metas[i].getAttribute("name") == "csrf-token") {  
        ajax.setRequestHeader("X-CSRF-Token", metas[i].getAttribute("content"));
    } 
}

See updated JavaScript code from this fiddle

从这个小提琴中查看更新的 JavaScript 代码