search
HomeBackend DevelopmentPHP Tutorial文本表单和图片一起进行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/imghwm/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/imghwm/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等)都没问题。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.