将数据传递到Jquery Ajax的正确方法 [英] Correct way to pass data to Jquery Ajax

查看:127
本文介绍了将数据传递到Jquery Ajax的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Whats the correct way to pass data to ajax using jquery. I have the following method and I want to pass the CSRF token from a meta tag but it doesn't work.

<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方法:

Laravel method to process the file:

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/

I've followed the documentation from the following source https://cmlenz.github.io/jquery-iframe-transport/

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

I get tokenmismatch error. Note this is using Laravel 5.1

*更新*

应该可以将令牌直接添加到data属性,因为csrf令牌已经在我的meta标签中.下面是在rails上使用ribs.js/ruby​​完成的示例,但是我不是骨干/rails的专家,因此如果有人可以将其转换为jquery,那将是有帮助的. ( http://estebanpastorino.com/2013 /09/27/simple-file-uploads-with-backbone-dot-js/)

Should be able to add the token directly to data attribute as the csrf token is already in my meta tag. Below is an example done using backbone.js/ruby on rails, but I'm not an expert on backbone/rails so if any one can translate that into jquery it would be helpful. (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传输的格式.

You've told jQuery to not convert the object containing your data into a format suitable for transmitting over HTTP.

这篇关于将数据传递到Jquery Ajax的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆