javascript 如何显示错误消息 Jquery ajax?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25638661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:46:52  来源:igfitidea点击:

How to display error messages Jquery ajax?

javascriptphpjqueryajax

提问by Hemal Sithul

I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.

我是一名学生,正在使用 jquery 和 php 向数据库添加记录。正在添加记录,但如果记录已成功添加,我想显示一条消息“插入记录”,如果发生错误,则显示一条错误消息。

This is my html code:

这是我的 html 代码:

<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
    <label id="name_label" class="control-label col-xs-2">Name</label>
    <div class="col-xs-10">
        <input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red"  id="name_error"></font>
    </div>
</div>

<div class="form-group">
    <label id="email_label" class="control-label col-xs-2">Email</label>
    <div class="col-xs-10">
        <input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red"  id="email_error"></font>
    </div>
</div>

<div class="form-group">
    <div class="col-xs-offset-2 col-xs-10">
        <button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>

    </div>
</div>

<div id="dialog"></div>
</form>

This is my registration-newsletter.php

这是我的注册newsletter.php

<?php
include('connect.php');

$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";


$result=mysql_query($query);
if(!$result){
    echo "Some error Occured..Please try later";
}
else{
    echo "Your details have been saved. Thank You ";
}

mysql_close($con);
?>

This is my JQuery code

这是我的 JQuery 代码

$(document).ready(function(){
$("#register-newsletter").click(function(){
    var name=$("#news_name").val();
    var email=$("#news_email").val();

    var dataString="name="+name+"&email="+email;
    var request;
        request = $.ajax({
        url: "registration-newsletter.php",
        type: "POST",           
        data: dataString
        });

    //return false;
});

});

回答by Jenz

Add a span to your html code for displaying error.

向您的 html 代码添加一个跨度以显示错误。

<span id="error"></span>

Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.

您已经将消息从 PHP 页面回显到 ajax。您可以执行 mysql_affected_rows() 来检查查询是否更新了表。

$result=mysql_query($query);
if(mysql_affected_rows()>0){    // return the number of records that are inserted
   echo "Your details have been saved. Thank You ";    // success
}
else{
    echo "Some error Occured..Please try later";   // failure
}
exit;

Then you can simply show the echoed message in the span with id erroras:

然后,您可以简单地将 id 显示在 span 中的回显消息error为:

request = $.ajax({
        url: "registration-newsletter.php",
        type: "POST",           
        data: dataString,
        success:function(response)     // response from requested PHP page
        {
           $('#error').html(response);  // set the message as html of span
        }
        });

回答by user3789888

  $.ajax({
                url: 'registration-newsletter.php',
                 type: 'post',
                 data:  dataString ,
                 success: function (msg) {
                  alert(msg);
                },
                error:function(msg)
                {
                alert(msg);
                }

            });

回答by Sundar

jQuery.ajax({
    url: "myfile.php",
    type: "POST",           
    data: dataString,
    success:function(response)     /* this response is an array which is returning from the myfile.php */
    {
    $status = response['status'];
    if($status == 'success')
        {
        $('#message').html(response['msg']);
        }
    else 
        {
        $('#message').html(response['msg']);
        }
    }
    });

The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.

您添加成功的函数将处理“要附加的文本”或“要显示的警报”。相当于if条件,如果响应成功,则进入条件。

回答by Ond?ej Sta?ek

This is what worked for me for form submit (see those 2 parameters to .thenfunction):

这是表单提交对我有用的方法(请参阅.then函数的那两个参数):

<span id="result">Loading...</span>
<div id="form">
    <form>
        <input id="personId"> <-- put personID here<br>
        <input id="submit" type="submit" value="Generate">
    </form>
</div>

<script type="application/javascript">
    $(document).ready(function() {
        var submit = $('#submit');
        var res = $('#result');
        $('#form').submit(function() {
            submit.prop('disabled', true);
            res.text("Sending message...");

            $.ajax({
                url: '/rest/message',
                contentType: "application/json;charset=UTF-8",
                method: "POST",
                data: JSON.stringify({'personId': $('#personId').val()})
            }).then(function(result) { // OK
                res.text("Message was generated");
                submit.prop('disabled', false);
            }, function(reason) { // ERROR
                res.css('color', 'red').css('font-weight','Bold');
                res.text("An error has occurred: " + reason.responseJSON.message);
                submit.prop('disabled', false);
            });
            return false; // prevent default action
        });
    });
</script>