表单操作,捕获响应

时间:2016-06-20 16:15:02

标签: php jquery

我制作了一个jquery移动应用,我需要上传图片,所以我使用了这段代码:

<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>

现在我需要以某种方式获取来自php的回声,告诉我上传成功或否,我该怎么办?

@Edit 这里有一些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;
}
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.";
//here i insert the info into db
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

?>

1 个答案:

答案 0 :(得分:0)

以下是如何使用php,理解它并从中进行改进的基本示例。

它可能不是你需要的直接答案,但它是一个良好的开端。

这个php代码返回一个json编码

<?php  
if ( isset($_FILES['fileToUpload']['name']) ) {
  if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], "path/to/upload/{$_FILES['fileToUpload']['name']}")) {
    $data['res'] =  "Success";
    echo json_encode($data);
  } else {
    $data['res'] = "Failed";
    echo json_encode($data);
  }
}

&GT;

和这个jquery,将通过php

捕获json返回
$(document).ready(function() {
  $('#submit').click(function() {
    var url = $(this).parent('form').attr('action');
    $.ajax({
      url:      url,
      type:     'post',
      dataType: 'json',
      data: $('form').serialize(),
      success:  function(data) {
        alert(data.res);
      }
      error:    function(data) {
        alert('error');
      }
    });
  });
});

希望这个帮助