繁体   English   中英

AJAX成功后页面不会刷新

[英]Page Doesn't Refresh after AJAX is successful

没有错误时,我的页面不会刷新。

我用了:

window.location.reload(true);

该操作data.success返回True时执行。

我是PHP和AJAX的新手,所以我以此为指导。 我知道如何处理到服务器的信息,但是我想显示消息而不离开页面。

PHP:

<?php

// connects to "ajax" database
mysql_connect("localhost", "root", "password");
mysql_select_db("ajax");


// assigns variables to fields
$name = $_POST['name'];
$email = $_POST['email'];
$superheroAlias = $_POST['superheroAlias'];


$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if (empty($_POST['superheroAlias']))
        $errors['superheroAlias'] = 'Superhero alias is required.';

// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        $sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";

        $query = @mysql_query($sql);

        header("location: /");

    }

    // return all our data to an AJAX call
    echo json_encode($data);

?>

JS

// magic.js
$(document).ready(function() {

// process the form
$('form').submit(function(event) {

    $('.form-group').removeClass('has-error'); // remove the error class
    $('.help-block').remove(); // remove the error text

    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'name'              : $('input[name=name]').val(),
        'email'             : $('input[name=email]').val(),
        'superheroAlias'    : $('input[name=superheroAlias]').val()
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'process.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
        encode      : true,
    })
        // using the done promise callback
        .done(function(data) {

            // log data to the console so we can see
            console.log(data); 

            // here we will handle errors and validation messages
            if (!data.success) {

                // handle errors for name ---------------
                if (data.errors.name) {
                    $('#name-group').addClass('has-error'); // add the error class to show red input
                    $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
                }

                // handle errors for email ---------------
                if (data.errors.email) {
                    $('#email-group').addClass('has-error'); // add the error class to show red input
                    $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
                }

                // handle errors for superhero alias ---------------
                if (data.errors.superheroAlias) {
                    $('#superhero-group').addClass('has-error'); // add the error class to show red input
                    $('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
                }

            } else {

                    window.location.reload(true);

            }
        })

        // using the fail promise callback
        .fail(function(data) {

            // show any errors
            // best to remove for production
            console.log(data);
        });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

});

您的代码中有很多错误。 首先,仅在出现错误时才执行AJAX调用的原因是因为在没有任何错误时要重新定位页面。

header("location: /");

是你的罪魁祸首。 您必须先重新定位页面,然后才能输出任何JSON。 第二,成功完成$ _POST传输后,您的$data变量不包含[success]键。 因此,即使您打算搬迁,您仍然不会输出任何有用的数据。 第三 ,您从未保存到MySQL数据库的链接,仅实例化了它。 此外,你会想用mysqli_因为mysql_已被弃用。

将前两行代码更改为此:

$link = new mysqli( "localhost", "root", "password", "ajax" );

将该if-statement更改为此:

if ( ! empty( $errors ) ) {
    $data["errors"] = $errors;
    $data["success"] = false;
} else {
    $data["success"] = true;
    $data["errors"] = $errors; // There are none, so this isn't neccessary

    $sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
    $link->query( $sql );
}

顺便说一句,我希望这仅是出于演示目的,因为那是一些可怕的验证/卫生措施。 如果不是,这里是一些有用的链接:

http://www.phpro.org/tutorials/Validating-User-Input.html-关于卫生/验证的深入教程http://php.net/manual/zh/book.mysqli.php-您的指南到MySQLi库。

删除header("location: /"); 从其他部分的PHP文件中。 我认为这将重定向页面,因此,您的回复与您想要的不一样。

Here If condition fails then check for $data in else and remove header from else.



     if ( ! empty($errors)) {

                // if there are items in our errors array, return those errors
                $data['success'] = false;
                $data['errors']  = $errors;
            } else {

                $sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";

                $query = @mysql_query($sql);
                $data['success'] = false;
                //header("location: /");

            }

            // return all our data to an AJAX call
            echo json_encode($data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM