文本表单和图片一起进行ajax提交,表单是值,图片是对象,发送时有些问题
代码如下:
<code> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/tether/1.1.1/css/tether.min.css" rel="stylesheet"> <div class="container"> <fieldset class="form-group"> <label for="title">标题</label> <input type="text" class="form-control" id="title" placeholder=""> </fieldset> <fieldset class="form-group"> <label for="content">内容</label> <textarea class="form-control" id="content" rows="3"></textarea> </fieldset> <fieldset class="form-group"> <label for="photo">图片</label> <input type="file" name="file" accept="image/*" class="form-control-file" id="photo"> <img src="/static/imghw/default1.png" data-src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js" class="lazy" id="preview" alt="文本表单和图片一起进行ajax提交,表单是值,图片是对象,发送时有些问题" > </fieldset> <a id="submit" class="btn btn-primary">submit</a> </div> <script></script> <script src="https://cdn.bootcss.com/tether/1.1.1/js/tether.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script> // 用到了localResizeIMG插件,压缩图片: https://github.com/think2011/localResizeIMG <script src="js/dist/lrz.all.bundle.js"></script> <script> $(function () { var $preview = $('#preview'); var formData = null; //压缩图片 $('#photo').on('change', function () { lrz(this.files[0], { width: 800 }).then(function (rst) { //图片预览 $preview.attr('src', rst.base64); //根据需要增加一些信息 rst.formData.append('fileLen', rst.fileLen); //压缩后的图片暂存在变量formData中 formData = rst.formData; }); }); //ajax请求 $("#submit").click(function () { //设置TOKEN $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url: "{{ url('article/') }}", dataType: 'json', processData: false, contentType: false, cache: false, data: { title: $("#title").val(), content: $("#content").val(), photo: formData } }).done(function (data) { alert(JSON.stringify(data)); }).fail(function (jqXHR, textStatus) { console.log(jqXHR); console.log(textStatus); }); }); }); </script> </code>
示例中,有两个文本表单,另外还有一张图片,一起提交到后台,
因为普通提交不能压缩图片,所以用js在前端压缩后,用ajax一起提交到后台,
提交过程中问题如下:
主要跟这两项相关:
<code>processData: false, contentType: false,</code>
1、如果让这两项生效,Request payload显示为:[object Object]
,ajax请求能成功发送,但jquery拿不到表单的值。
2、如果注释掉这两项,谷歌浏览器控制台报错:Uncaught TypeError: Illegal invocation
,ajax请求不能发送。
不知怎么弄
回复内容:
代码如下:
<code> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/tether/1.1.1/css/tether.min.css" rel="stylesheet"> <div class="container"> <fieldset class="form-group"> <label for="title">标题</label> <input type="text" class="form-control" id="title" placeholder=""> </fieldset> <fieldset class="form-group"> <label for="content">内容</label> <textarea class="form-control" id="content" rows="3"></textarea> </fieldset> <fieldset class="form-group"> <label for="photo">图片</label> <input type="file" name="file" accept="image/*" class="form-control-file" id="photo"> <img src="/static/imghw/default1.png" data-src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js" class="lazy" id="preview" alt="文本表单和图片一起进行ajax提交,表单是值,图片是对象,发送时有些问题" > </fieldset> <a id="submit" class="btn btn-primary">submit</a> </div> <script></script> <script src="https://cdn.bootcss.com/tether/1.1.1/js/tether.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script> // 用到了localResizeIMG插件,压缩图片: https://github.com/think2011/localResizeIMG <script src="js/dist/lrz.all.bundle.js"></script> <script> $(function () { var $preview = $('#preview'); var formData = null; //压缩图片 $('#photo').on('change', function () { lrz(this.files[0], { width: 800 }).then(function (rst) { //图片预览 $preview.attr('src', rst.base64); //根据需要增加一些信息 rst.formData.append('fileLen', rst.fileLen); //压缩后的图片暂存在变量formData中 formData = rst.formData; }); }); //ajax请求 $("#submit").click(function () { //设置TOKEN $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url: "{{ url('article/') }}", dataType: 'json', processData: false, contentType: false, cache: false, data: { title: $("#title").val(), content: $("#content").val(), photo: formData } }).done(function (data) { alert(JSON.stringify(data)); }).fail(function (jqXHR, textStatus) { console.log(jqXHR); console.log(textStatus); }); }); }); </script> </code>
示例中,有两个文本表单,另外还有一张图片,一起提交到后台,
因为普通提交不能压缩图片,所以用js在前端压缩后,用ajax一起提交到后台,
提交过程中问题如下:
主要跟这两项相关:
<code>processData: false, contentType: false,</code>
1、如果让这两项生效,Request payload显示为:[object Object]
,ajax请求能成功发送,但jquery拿不到表单的值。
2、如果注释掉这两项,谷歌浏览器控制台报错:Uncaught TypeError: Illegal invocation
,ajax请求不能发送。
不知怎么弄
看了以下,这个插件是利用了FormData
对象来发送文件的,所以你用jQuery.ajax()
发送的数据的data
属性必须是FormData
对象,不能把FormData
对象再作为data
属性的子属性。
<code>$.ajax({ type: "POST", url: "{{ url('article/') }}", dataType: 'json', processData: false, contentType: false, cache: false, data: { title: $("#title").val(), content: $("#content").val(), photo: formData //这里错了,不能把FormData对象作为data属性的子属性 } }) </code>
应该是这样才对:
<code>$.ajax({ type: "POST", url: "{{ url('article/') }}", dataType: 'json', processData: false, contentType: false, cache: false, data: formData //直接把formData对象作为data属性的值发送 }) </code>
如果你要附加字段,可以用FormData
对象的append
方法:
<code>//这段代码要在ajax请求之前 formData.append('title', $("#title").val()); formData.append('content',$("#content").val()); </code>
如果你要想把图片文件的字段名设置成photo
,在localResizeIMG参数文档力其实已经说明了,就是在你压缩图片的代码那里这样修改:
<code>lrz(this.files[0], { width: 800, fieldName: 'photo' //把上传图片文件的字段设置为photo }) </code>
另外要注意,FormData
对象在IE上只有版本10以上才支持,其他现代浏览器(Firefox、Chrome、Safari、MS Edge等)都没问题。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
