如何使用$ .ajax()输入字段文本和文件上传?

编程入门 行业动态 更新时间:2024-10-23 02:11:02
本文介绍了如何使用$ .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()输入字段文本和文件上传?

本文发布于:2023-10-11 22:44:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483049.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   如何使用   文件上传   ajax   文本和

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!