简体   繁体   English

XMLHttpRequest-Laravel

[英]XMLHttpRequest - Laravel

I am uploading a file with laravel and using ajax request to create the progress bar for it. 我正在使用laravel上传文件,并使用ajax请求为其创建进度栏。 This is how the form action routes to the controller: 这是表单操作路由到控制器的方式:

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

ajax: 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'
));

Simply use JavaScript to get the form action attribute 只需使用JavaScript即可获取表单操作属性

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

First: 第一:

Don't mix onclick event on submit button, clicking submit button actually process the form itself. 不要在提交按钮上混合onclick事件,单击提交按钮实际上会处理表单本身。 Its better to bind submit events to forms instead of binding click events on submit button. 最好将提交事件绑定到表单,而不是将提交按钮上的单击事件绑定。

By giving a name attribute to your form like name="my_form" , you can add submit event handler to your form. 通过给表单一个name属性,例如name="my_form" ,您可以向表单中添加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. 您的函数uploadfile(..)将接受一个称为URL的参数。 Which will be passed to ajax.open(..) method 它将被传递给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. 在当前表单视图文件的<head> <meta >标记内的<meta >标记下添加。

<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代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM