首页 \ 问答 \ 如何在jQuery中使用Ajax请求发送FormData对象?(How to send FormData objects with Ajax-requests in jQuery? [duplicate])

如何在jQuery中使用Ajax请求发送FormData对象?(How to send FormData objects with Ajax-requests in jQuery? [duplicate])

这个问题已经在这里有一个答案:

  • 用jQuery.ajax发送multipart / formdata 10个答案

XMLHttpRequest Level 2标准(仍然是工作草案)定义了FormData接口。 此接口可将File对象附加到XHR请求(Ajax请求)。

Btw,这是一个新功能 - 在过去,“隐藏的iframe-trick”被使用(在我的另一个问题中阅读 )。

这是它的工作原理(示例):

var xhr = new XMLHttpRequest(),
    fd = new FormData();

fd.append( 'file', input.files[0] );
xhr.open( 'POST', 'http://example.com/script.php', true );
xhr.onreadystatechange = handler;
xhr.send( fd );

其中input是一个<input type="file">字段, handler是Ajax请求的成功处理程序。

这在所有的浏览器(除IE之外,再次)都非常出色。

现在,我想使这个功能与jQuery。 我试过这个:

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.post( 'http://example.com/script.php', fd, handler );

不幸的是,这不会工作(抛出“非法调用”错误 - 屏幕截图在这里 )。 我假设jQuery期望一个表示form-field-names / values的简单键值对象,并且我传入的FormData实例显然是不兼容的。

现在,由于可以将FormData实例传递到xhr.send() ,我希望它也可以使其与jQuery一起工作。


更新:

我在jQuery的Bug Tracker创建了一个“功能票”。 在这里: http : //bugs.jquery.com/ticket/9995

我被建议使用“Ajax preilter”...


更新:

首先让我演示一下演示我想要实现的行为。

HTML:

<form>
    <input type="file" id="file" name="file">
    <input type="submit">
</form>

JavaScript的:

$( 'form' ).submit(function ( e ) {
    var data, xhr;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    xhr = new XMLHttpRequest();

    xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true );
    xhr.onreadystatechange = function ( response ) {};
    xhr.send( data );

    e.preventDefault();
});

上述代码导致此HTTP请求:

multipartformdata

这就是我需要的 - 我想要这个“multipart / form-data”的内容类型!


拟议的解决方案如下:

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

但是,这导致:

wrongcontenttype

您可以看到,内容类型错误...


This question already has an answer here:

The XMLHttpRequest Level 2 standard (still a working draft) defines the FormData interface. This interface enables appending File objects to XHR-requests (Ajax-requests).

Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in my other question).

This is how it works (example):

var xhr = new XMLHttpRequest(),
    fd = new FormData();

fd.append( 'file', input.files[0] );
xhr.open( 'POST', 'http://example.com/script.php', true );
xhr.onreadystatechange = handler;
xhr.send( fd );

where input is a <input type="file"> field, and handler is the success-handler for the Ajax-request.

This works beautifully in all browsers (again, except IE).

Now, I would like to make this functionality work with jQuery. I tried this:

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.post( 'http://example.com/script.php', fd, handler );

Unfortunately, that won't work (an "Illegal invocation" error is thrown - screenshot is here). I assume jQuery expects a simple key-value object representing form-field-names / values, and the FormData instance that I'm passing in is apparently incompatible.

Now, since it is possible to pass a FormData instance into xhr.send(), I hope that it is also possible to make it work with jQuery.


Update:

I've created a "feature ticket" over at jQuery's Bug Tracker. It's here: http://bugs.jquery.com/ticket/9995

I was suggested to use an "Ajax prefilter"...


Update:

First, let me give a demo demonstrating what behavior I would like to achieve.

HTML:

<form>
    <input type="file" id="file" name="file">
    <input type="submit">
</form>

JavaScript:

$( 'form' ).submit(function ( e ) {
    var data, xhr;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    xhr = new XMLHttpRequest();

    xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true );
    xhr.onreadystatechange = function ( response ) {};
    xhr.send( data );

    e.preventDefault();
});

The above code results in this HTTP-request:

multipartformdata

This is what I need - I want that "multipart/form-data" content-type!


The proposed solution would be like so:

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

However, this results in:

wrongcontenttype

As you can see, the content type is wrong...


原文:https://stackoverflow.com/questions/6974684
更新时间:2023-04-16 10:04

最满意答案

您可能在该服务器中运行了多个cron进程。 这通常不会发生。 但无论如何确认它

 ps aux | grep cron

你可以阻止它,

/etc/init.d/cron stop

要么

service cron stop

或使用'杀死PID'(不推荐)。

并开始使用start - 而不是停在上​​面两个命令中的任何一个。


You may have more than one cron process running in that server. This normally wont happen. But anyway confirm it with

 ps aux | grep cron

You can stop it by,

/etc/init.d/cron stop

or

service cron stop

or use 'kill PID' ( not recommended ).

And to start use start - instead of stop in either of above two commands.

相关问答

更多
  • crontab命令仅在最小环境变量下执行,即 PATH=/usr/bin:/bin (无论如何都是debian), 因此,如果您依赖于$PATH ,它将失败。 考虑指定渗透程序的绝对路径,无论它在何处被调用。 或者,您可以在脚本中更改$PATH本身 export PATH="/my/bin:$PATH" ps:您可以通过添加简单的cron作业来检查环境 * * * * * env > /tmp/env.txt crontab commands are executed only with minimal ...
  • 您可能在该服务器中运行了多个cron进程。 这通常不会发生。 但无论如何确认它 ps aux | grep cron 你可以阻止它, /etc/init.d/cron stop 要么 service cron stop 或使用'杀死PID'(不推荐)。 并开始使用start - 而不是停在上面两个命令中的任何一个。 You may have more than one cron process running in that server. This normally wont happen. Bu ...
  • 语法* * * * * /var/www/html/testsession.php > /var/www/html/log有效。 很可能,因为它是crontab中的最后一行,它缺少换行符。 Cron在每个条目的末尾都需要换行; 换句话说,你的crontab必须以空行结束。 从man crontab的“诊断”部分: cron要求crontab中的每个条目以换行符结尾。 如果crontab中的最后一个条目缺少换行符,cron将认为crontab(至少部分)已损坏并拒绝安装它。 您可能希望将>替换为>>以便将新内 ...
  • 这取决于你的crontab中的内容。 如果在其中设置了任何环境变量,则应该检查并修复它们。 除此之外,你应该没问题。 你的shell(应该)已经停止尝试在第一个*执行每一行,除非扩展本身产生了一个有效的命令。 It depends on what was in your crontab. If you set any environment variables in it, you should probably check and fix them. Apart from that, you should ...
  • 我不知道为什么不运行但是在那之前发生了同样的事情 * * * * * / home / [user] / pushDelivery 尝试这个 * / 1 * * * * / home / [user] / pushDelivery 它以这种方式为我工作......(每一分钟都有任务) I fixed the issue. In my pushDelivery file I was supposed to write: /usr/bin/flock -n /home/[user]/PushChatServer ...
  • 你缺少环境变量。 尝试这样的简单测试 将此添加到您的crontab * * * * * set > /tmp/vars 等待2-3分钟,返回并删除刚刚创建的crontab条目。 下一个, 从通常使用的shell命令行 set > myvars diff myvars /tmp/vars 这将向您展示环境的不同之处。 修改您的cron作业环境。 只需添加所需内容即可。 You are missing envrionment variables. Try a simple test like this a ...
  • * * * * * su esr -c "DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$(ps -au esr | grep -i "gnome-session" | awk '{ print $1 }')/environ | sed -e 's/DBUS_SESSION_BUS_ADDRESS=//') $(whereis notify-send | awk '{ print $2 }') -u normal -t 2 ...
  • 假设我有一个带有内容的python文件test.py print "hello" 要安排它每30分钟运行一次,请使用 crontab -e 然后编辑添加 */30 * * * * python /path-to-file/test.py 检查cron是否成功运行 grep CRON /var/log/syslog 在这里,你会看到日志,线条等 May 31 14:25:01 shivam-PC CRON[17805]: (shivam) CMD (python /home/shivam/test.py ...
  • 我发现了导致我的错误的原因(其他人可能/可能不同)。 通过许多源文件调试后,我发现问题的根源是没有加载PDO扩展。 我不知道为什么只有在作为一个cron-job运行时才是这种情况。 需要注意的是:似乎其他具有相同问题的人在配置阶段经常会遇到这种情况,因此如果您获得相同的异常,从那里开始调试可能是个好主意。 I've found what was causing my error in particular (it may/may not vary for others). After debugging t ...
  • 在crontab -e ,将其crontab -e第一行: PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 然后wget应该工作而不指定完整路径。 您也可以只指定wget的完整路径(找到它的which wget ): /usr/bin/wget --output-document="/Users/proudowner/Desktop/tfgo/bp.json" http://backpack.tf/api/IGetMark ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)