使用表单数据通过ajax将数据发送到PHP

Send data to PHP with ajax using formdata

本文关键字:数据 PHP 表单 ajax      更新时间:2024-01-29

解决方案:我不得不放弃sumbmit按钮并使用常规按钮。此代码的其余部分正常工作。我还删除了HTML表单。

我正在尝试使用表单数据用ajax向我的php脚本发送一个图像+一些文本。这就是我得到的:

$ajax_uploadImage = function (form)
{
    var data = new FormData();
    data.append('title', form.find('#title').val());
    data.append('comment', form.find('#comment').val());
    data.append('image', form.find('#image').prop('files')[0]);
    $.ajax({
        url: '../php/upload_image.php',
        data: data,
        type: 'POST',
        processData: false,
        contentType: false,
        success: function (data) {
            alert('something');
        }
    });
}

函数参数中的表单是一个普通的html表单,这里是html:中的表单

<form enctype="multipart/form-data" id="upload_image">
    <label for="title">Title:</label>
        <input type="text" id="title" name="title" />
    <br />
    <label for="comment">Comment:</label>
    <input type="text" id="comment" name="comment" />
    <br />
    <label for="image">Image:</label>
    <input type="file" id="image" name="image" />
    <br />
    <input type="submit" value="Upload picture" name="submit">
    <hr />
</form>

成功的警觉性永远不会触发,有人能帮上忙吗?

编辑:添加PHP,即使它什么都不做:

<?php echo 'something'; ?>

现在您正在FormData中存储一个jQuery对象,该对象无法工作。请改用这些元素的值。在文件输入的情况下,您需要使用DOM元素的files属性中的File对象:

data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);

尝试添加表单操作,如:

<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">