ajax正在运行而没有event.preventDefault(); - 如果添加了event.preventDefault(),则会中断;

时间:2016-07-25 15:59:02

标签: javascript php jquery mysql ajax

我已经构建了一个AJAX请求来向mySql插入一个新行并将更新后的数据库作为一个数组返回。它在没有event.preventDefault();的情况下完美运行(并重定向到PHP文件) - 但是当我添加event.preventDefault();以防止重定向时,它会中断。

有什么想法吗?

$("#upload-form").submit(function() {
    //event.preventDefault();
    window.alert(paintsCatlg.length);

    document.querySelector("#upload-form #id").value = paintsCatlg.length;
    document.querySelector("#upload-form #src").value = "paintings//" + document.querySelector("#upload-form #exhibition_en").value + "//" + fileName;
    window.alert(document.querySelector("#upload-form #id").value);
    window.alert(document.querySelector("#upload-form #src").value);

    var uploadForm = new FormData();
    uploadForm.append("id", $('#id').val());
    uploadForm.append("src", $('#src').val());
    uploadForm.append("title_en", $('#title_en').val());
    uploadForm.append("title_he", $('#title_he').val());
    uploadForm.append("exhibition_en", $('#exhibition_en').val());
    uploadForm.append("exhibition_he", $('#exhibition_he').val());
    uploadForm.append("subjects_en", $('#subjects_en').val());
    uploadForm.append("subjects_he", $('#subjects_he').val());
    uploadForm.append("keywords_en", $('#keywords_en').val());
    uploadForm.append("keywords_he", $('#keywords_he').val());
    uploadForm.append("height", $('#height').val());
    uploadForm.append("width", $('#width').val());
    uploadForm.append("sold", $('#sold').val());
    var settings = {
        // "async": true,
        // "crossDomain": true,
        "url": "upload.php",
        "method": "POST",
        "dataType": 'json',
        "processData": false,
        "contentType": false,
        "mimeType": "multipart/form-data",
        "data": uploadForm
    }

    $.ajax(settings).success(function(data) {
        //   alert("Hello! I am an alert box!!");
        alert('good');
        alert(data);
        paintsCatlg = data;
    });
});
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chana_goldberg";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

// if(isset($_POST['submit'])) {
//   unset($_POST['submit']);
$id = $_POST['id'];    
$src = $_POST['src'];
$title_en = $_POST['title_en'];
$title_he = $_POST['title_he'];
$exhibition_en = $_POST['exhibition_en'];
$exhibition_he = $_POST['exhibition_he'];
$subjects_en = $_POST['subjects_en'];
$subjects_he = $_POST['subjects_he'];
$keywords_en = $_POST['keywords_en'];
$keywords_he = $_POST['keywords_he'];
$height = $_POST['height'];
$width = $_POST['width'];
$sold = $_POST['sold'];
$enc_exhibition = mb_convert_encoding($exhibition_en, "ASCII");
$target_dir = "paintings/$enc_exhibition/";
// $src = "paintings/$enc_exhibition/";
if ( ! is_dir($target_dir)) {
    mkdir($target_dir);
}

$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 if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $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)) {
        $exhibition_en = mysql_real_escape_string($exhibition_en);

        $stmt = $conn->prepare("INSERT INTO paintings_catalog (src, title_en, title_he, exhibition_en, exhibition_he, subjects_en, subjects_he, keywords_en, keywords_he, height, width, sold) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssiiss", $src, $title_en, $title_he, $exhibition_en, $exhibition_he, $subjects_en, $subjects_he, $keywords_en, $keywords_he, $height, $width, $sold);

        $stmt->execute();

        $query = "SELECT * FROM paintings_catalog ORDER BY id";
        $result = $conn->query($query);

        // numeric array
        $paintsCatlg[] = array(1 =>'');
        while ($row = $result->fetch_array(MYSQLI_NUM)){
            $paintsCatlg[] = $row;


        };

        echo json_encode($paintsCatlg);
    }
}

2 个答案:

答案 0 :(得分:2)

您需要使用提供给submit处理函数的事件参数,而不是全局事件对象。试试这个:

$("#upload-form").submit(function(e) { // note 'e' here
    e.preventDefault();
    // your code...
});

答案 1 :(得分:1)

您忘记将事件参数添加到函数

        $("#upload-form").submit(function(event){

          //event.preventDefault();
          window.alert(paintsCatlg.length);