Jquery用ajax发布图像

时间:2016-06-20 19:21:21

标签: php jquery ajax

我正在制作一个上传图片的jquery移动应用程序。

我使用了这段代码但是没有ajax你就无法从服务器捕获回声(这个完美无缺)

<form action="http://tipsnow.altervista.org/upload.php" method="post" enctype="multipart/form-data">
            Title: <input type="text" name="title" id="title" />
            Question Text: <input type="text" name="text" id="text" />
            <input type="hidden" id="idUtente" name="idUtente" value="">
            Select image to upload:
            <input type="file" name="fileToUpload" id="fileToUpload">
            <input type="submit" value="Upload Image" name="submit">
        </form>

所以我实现了ajax帖子:

html代码:

<form action="">
                    Title: <input type="text" name="title" id="title" />
                    Question Text: <input type="text" name="text" id="text" />
                    <input type="hidden" id="idUtente" name="idUtente" value="">
                    Select image to upload:
                    <input type="file" name="fileToUpload" id="fileToUpload">
                    <input type="submit" value="Upload Image" name="submit">
                </form>

jquery代码:

$(document).ready(function () {

            $('form').submit(function () {
                var title = document.getElementById('title').value;
                var idUtente = sessionStorage.getItem('autenticato').toString();
                var text = document.getElementById('text').value;
                var fileToUpload = document.getElementById('fileToUpload').files[0];

                var formData = new FormData();
                formData.append('title', title);
                formData.append('text', text);
                formData.append('idUtente', idUtente);
                formData.append('fileToUpload', fileToUpload);
                $.ajax({
                    url: 'http://tipsnow.altervista.org/upload.php',
                    data: formData,
                    type: 'post',
                    dataType: 'text',
                    contentType: false,
                    enctype: 'multipart/form-data',
                    processData: false,
                    success: function (data) {
                        alert(data);
                        return false;
                    }
                })
            });

php代码:

    <?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

但是只要我按下提交按钮,它就会把我带到应用程序的第一页而不上传任何内容,我认为这意味着ajax不成功,但问题是什么?

@edit注意到我没有附加提交按钮,做了但仍然没有工作

@@ edit:提交后28秒取得成功,但它没有上传img,也没有回复回声

@@@编辑: request

response

2 个答案:

答案 0 :(得分:0)

比每个人制作它容易得多。

只需将表单元素传递给FormData构造函数即可。具有name属性(包括文件)的输入元素的所有值都将传递给PHP脚本。

此外,您需要使用e.preventDefault();来停止提交表单。

$('form').submit(function (e) {
    e.preventDefault(); 

    // 'this' refers to this current form element 

    $.ajax({
        type: 'post',
        url: 'http://tipsnow.altervista.org/upload.php',
        data: new FormData(this), // important
        contentType: false, // important
        processData: false, // important
        success: function (data) {
            alert(data);
            return false;
        }
    })
});

答案 1 :(得分:-1)

首先你必须在提交后停止行动

$( this ).serialize()

实施后检查浏览器控制台(例如在firefox中你有firebug)你得到了什么数据

从您可以使用的表格中获取数据:

{{1}}

检查:https://api.jquery.com/serialize