【问题标题】:Page Doesn't Refresh after AJAX is successfulAJAX成功后页面不刷新
【发布时间】:2014-07-26 06:00:09
【问题描述】:

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

我用过:

window.location.reload(true);

应该data.success返回True时执行。

我是 PHP 和 AJAX 的新手,所以我使用 this 作为指南。我知道如何处理信息到服务器,但我想在不离开页面的情况下显示消息。

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();
});

});

【问题讨论】:

  • 能否在传递给done函数的anonymous function中使用断点,看看控件是否往那里走?
  • 如果你在window.location.reload(true);上面做一个console.log(data),你会得到什么

标签: javascript php jquery ajax


【解决方案1】:

您的代码中有很多错误。首先,您的 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/en/book.mysqli.php -- MySQLi 库指南。

【讨论】:

  • 这不起作用,删除标题位置也不起作用。我不知道问题是什么。我是前端开发人员,不是后端。
  • @Matthew 你有什么错误吗?这些在调试时非常有用。
  • 它不发送任何东西。 :P
  • 我会继续玩弄它
  • 好吧,祝你好运。以为我能帮上忙。检查浏览器控制台是否有 JS 错误,并确保 PHP 处于调试模式。
【解决方案2】:

从您的 php 文件的 else 部分中删除 header("location: /");。 我认为这会重定向页面,所以你的反应不是你想要的。

【讨论】:

    【解决方案3】:
    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);
    

    【讨论】:

      猜你喜欢
      • 2016-10-09
      • 2015-10-19
      • 2018-01-24
      • 1970-01-01
      • 2018-05-09
      • 2017-02-27
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多