【问题标题】:How I can send in ajax request file with other string's variables?如何发送带有其他字符串变量的 ajax 请求文件?
【发布时间】:2014-12-29 02:56:25
【问题描述】:

我正在尝试创建 ajax 调用并使用文件和其他变量发送数据,如果有帮助,我也会使用 django。

我的尝试:

js文件:

$("#save-new-request-testBtn").click(function(){
var project = $('#project').val();
var newRequestStreams = $('#newRequestStreams').val();
var request_bot_file = $('#request_bot_file')[0].files;

submit_new_request(project,newRequestStreams,request_bot_file );    

});

 function submit_new_request(project,newRequestStreams,request_bot_file ){
url= "add/submit";
console.log(project);
var new_data;

csfr();
$.ajax({
     async:false,
     url: url,
     type: "POST",
     enctype: 'multipart/form-data',
     data: ({project:project,newRequestStreams:newRequestStreams,request_bot_file :request_bot_file }),
     success: function(data){
         new_data= data;

         console.log(data);
     },
     error: function(xhr, status, error) {
                    $("#formError").html(xhr.responseText);
                    console.log(xhr.responseText);

                 }
});
console.log('fgcfg');

return new_data;

}

问题在于文件的选择: 未捕获的 InvalidStateError:无法从“HTMLInputElement”读取“selectionDirection”属性:输入元素的类型(“文件”)不支持选择。

有什么好的建议如何让它发挥作用?

谢谢, 冷杉

【问题讨论】:

  • 你有什么问题?
  • 这是正确的方法吗?因为它不起作用?
  • 哪个部分不完全工作?
  • 准确查找问题。
  • 问题在于文件的选择:未捕获的 InvalidStateError:无法从“HTMLInputElement”读取“selectionDirection”属性:输入元素的类型(“文件”)不支持选择。

标签: jquery ajax django html file-upload


【解决方案1】:

您需要在https://github.com/douglascrockford/JSON-js 下载 JSON.js 或 JSON2.js。 并执行以下操作:

var myDataToSend = JSON.stringify(
    {
        project: project,
        newRequestStreams : newRequestStreams,
        request_bot_file : request_bot_file
    }
);

还有 ajax 帖子:

$.ajax({
    url : url,
    type : "POST",
    enctype : 'multipart/form-data',
    data : 'data=' + myDataToSend ,
    success : function(){},
    error : function(){},
})

后端是什么语言,例如PHP你可以做:

$jsonArr = json_decode($_POST['data']);

获取 json_decode 在您的语言中的等效项。 Python 将是:

# Python 2.6+
import json
result = json.loads(post_variable_data_from_ajax)

【讨论】:

  • THE OP 标记 Django,因此后端似乎是 python。
  • 问题在于文件的选择:未捕获的 InvalidStateError:无法从“HTMLInputElement”读取“selectionDirection”属性:输入元素的类型(“文件”)不支持选择。
猜你喜欢
  • 1970-01-01
  • 2018-06-03
  • 2014-06-25
  • 1970-01-01
  • 2012-12-18
  • 2021-10-12
  • 2013-11-03
  • 2015-09-22
相关资源
最近更新 更多