将数据传递给 Jquery Ajax 的正确方法

Correct way to pass data to Jquery Ajax

本文关键字:方法 Ajax Jquery 数据      更新时间:2023-09-26

使用 jquery 将数据传递给 ajax 的正确方法是什么?我有以下方法,我想从元标记传递 CSRF 令牌,但它不起作用。

<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/

我收到令牌不匹配错误。请注意,这是使用Laravel 5.1

*更新*

应该能够将令牌直接添加到数据属性,因为 csrf 令牌已经在我的元标记中。下面是一个在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 传输的格式。

您需要将其添加到您的页面:

$(function() {
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN' : '{{ csrf_token() }}' } });
});

这是因为每次向服务器发送 AJAX 请求,AJAX 都需要X-CSRF-TOKEN(除非您将其关闭,我不建议这样做)。

资料来源:我自己与Laravel的经历。