使用 jquery 将数据传递到 ajax 的正确方法是什么?我有以下方法,我想从元标记传递 CSRF token ,但它不起作用。
<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="fallback">
<input type="file" name="logo" id="logo" class="inputfile"/>
</div>
$(document).on("change", ".fallback .inputfile", function() {
$.ajax({
url: "/upload",
type: 'POST',
cache: false,
data: {
_token: $('meta[name="csrf-token"]').attr('content')
},
files: $(":file", this),
iframe: true,
processData: false
}).complete(function(data) {
console.log(data);
// $('#img-thumb').attr('src', data.path);
// $('input[name="job_logo"]').val(data.path);
});
});
Laravel 处理文件的方法:
public function upload(Request $request) {
if($request->hasFile('logo')) {
//upload an image to the /img/tmp directory and return the filepath.
$file = $request->file('logo');
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$tmpFilePath = '/img/tmp/';
$file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
$path = $tmpFilePath . $tmpFileName;
return response()->json(['path'=> $path], 200);
} else {
return response()->json(false, 200);
}
}
我已遵循以下来源的文档 https://cmlenz.github.io/jquery-iframe-transport/
我收到 token 不匹配错误。请注意,这是使用 Laravel 5.1
* 更新 *
应该能够将 token 直接添加到数据属性,因为 csrf token 已经在我的元标记中。下面是在 Rails 上使用backbone.js/ruby 完成的示例,但我不是backbone/rails 方面的专家,因此如果有人可以将其转换为jquery,那将会很有帮助。 (http://estebanpastorino.com/2013/09/27/simple-file-uploads-with-backbone-dot-js/)
uploadFile: function(event) {
var values = {};
var csrf_param = $('meta[name=csrf-param]').attr('content');
var csrf_token = $('meta[name=csrf-token]').attr('content');
var values_with_csrf;
if(event){ event.preventDefault(); }
_.each(this.$('form').serializeArray(), function(input){
values[ input.name ] = input.value;
})
values_with_csrf = _.extend({}, values)
values_with_csrf[csrf_param] = csrf_token
this.model.save(values, { iframe: true,
files: this.$('form :file'),
data: values_with_csrf });
}
最佳答案
processData: false
您已告诉 jQuery 不要将包含数据的对象转换为适合通过 HTTP 传输的格式。
关于javascript - 将数据传递给 Jquery Ajax 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343814/