如何使用$ .ajax()输入字段文本和文件上传? [英] How to use $.ajax() for input field text AND FILE upload?

查看:117
本文介绍了如何使用$ .ajax()输入字段文本和文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

                        $.ajax({
                            type: 'post',
                            url: '../lib/upload.php',
                            data: new FormData( $("#niceidentifier") ),
                            processData: false,
                            contentType: false,
                            success: function (response) {
                                if(response == 'success') {
                                    return true;
                                }
                                else {
                                    alert(response);
                                    console.log(response);
                                }
                            }
                        });

HTML表单只是基本的HTML(包括enctype和method post),但不幸的是没有数据被传递。如何上传文件并传递一次输入数据?

The HTML form is just basic HTML (enctype included and method post) but unfortunately NO data is passed. How can I upload a file AND pass the input data once?

推荐答案

您可以使用 FormData 通过文件。和processData,contentType设置为false强制。因为你不打算在客户端处理文件。

You can use FormData to pass the File. and processData,contentType set to false compulsory. because you are not going to process file in client side.

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
        data.append('myFile', value);   //No I18N
});


$.ajax({
    url: '/your-url', 
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',   //No I18N
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
    // do something
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
            // Handle errors here
    }
});

或者您可以使用以下数据发送文件:

$( '#formId' )
  .submit( function( e ) {
 e.preventDefault();
 $.ajax({
    url: '/your-url', 
    type: 'POST',
    data: new FormData( this ),
    cache: false,
    dataType: 'json',   //No I18N
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
    // do something
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
            // Handle errors here
    }
});
});

这篇关于如何使用$ .ajax()输入字段文本和文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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