zoukankan      html  css  js  c++  java
  • 关于jquery post 文件和文本信息 而不刷新页面

    With Safari 5/Firefox 4, it’s easiest to use the FormData class:

    var data =newFormData();
    jQuery.each($('#file')[0].files,function(i, file){
        data.append('file-'+i, file);});
     

    So now you have a FormData object, ready to be sent along with the XMLHttpRequest.

    复制代码
    $.ajax({
        url:'php/upload.php',
        data: data,
        cache:false,
        contentType:false,
        processData:false,
        type:'POST',
        success:function(data){
            alert(data);}});
    复制代码
     

    It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

    You may now retrieve the file in PHP using:

    $_FILES['file-0']

    (There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)

    FormData

    XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个"表单".比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.

    想要更详细的了解如何使用FormData对象, 请查看使用FormData对象.

    构造函数

    new FormData (optional HTMLFormElement form)
     

    参数

    form
    (可选) 一个HTML表单元素,可以包含任何形式的表单控件,包括文件输入框.

    方法

    append()

    给当前FormData对象添加一个键/值对.

    new FormData (optional HTMLFormElement form)
    参数值
    name
    字段名称.
    value
    字段值.可以是,或者一个字符串,如果全都不是,则该值会被自动转换成字符串.
    filename
    (可选) 指定文件的文件名,当value参数被指定为一个Blob对象或者一个File对象时,该文件名会被发送到服务器上,对于Blob对象来说,这个值默认为"blob".

    注:如果你将一个Blob对象作为字段值添加到一个FormData对象中,则在使用Ajax将这个FormData对象提交到服务器上时,提交数据中代表对应文件的文件名的"Content-Disposition"字段的值可能会因浏览器的不同而不同,规范中规定为"blob",Gecko早期实现版本中为空字符串,查看下面的Gecko附注.

    浏览器兼容性

    FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
    Basic support 7+ 4.0 (2.0) 10+ 12+ 5+
    支持filename参数 (Yes) 22.0 (22.0) ? ? ?

    Gecko附注

    在Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4)之前,如果你将Blob对象作为数据添加到一个FormData对象中,则在使用Ajax将这个FormData对象提交到服务器上时,所发送的HTTP请求头中代表那个Blob对象所包含文件的文件名称的"Content-Disposition"请求头的值会是一个空字符串,这会引发某些服务器程序上的错误.从Gecko 7.0开始,这种情况下发送的文件名称改为"blob"这个字符串.

  • 相关阅读:
    python中a = a+b与a += b的不同
    python中的全局变量global
    python中星号(*)和双星号(**)的用法
    python循环语句
    python逻辑运算符
    python内置函数 print()
    python 解析迅雷下载链接
    python 正则表达式
    python 读写文件
    python selenium操作cookie
  • 原文地址:https://www.cnblogs.com/ifutan/p/jquery-post-files-when.html
Copyright © 2011-2022 走看看