我不会将此标记为重复,但您实际上是在询问使用 jQuery 显示通知的最佳方式。那是asked before。简而言之,在您的基本设置中,您需要做的就是显示一个 div 并将其淡入,但是有很多插件可以处理更多情况。
就向他们显示插入的客户或其他内容而言,您所要做的就是从服务器返回一个 JSON 响应,并使用您的 AJAX 请求的成功回调来处理它。然后,您将可以访问从服务器传回的数据。
进一步解释一下:您似乎要求做的是如何使用 Ajax 向服务器发送请求,获得一切按预期进行的通知,然后根据发生的情况在网页中显示通知.如果这是正确的,我将继续进行这些假设。
让我们整理一个简单的表单,将新客户添加到一个虚构的网站。它可能看起来像这样:
<form action='add_customer.php' method='POST' id='add_customer_form'>
First Name: <input type='text' name='first_name'><br>
Last Name: <input type='text' name='last_name'><br>
Email: <input type='text' name='email'><br>
<input type='submit' value='Add Customer'>
</form>
现在,我们用于处理此表单提交(通过 AJAX)的幼稚、不安全 PHP 代码可能看起来像这样。我说幼稚和不安全是因为你会做更多的数据验证(因为你从不相信来自客户端的任何东西)并且肯定需要清理数据以防止 SQL 注入。然而,这是一个示例,所以它可能看起来像这样:
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
if(mysql_query("
INSERT INTO customers
(first_name, last_name, email)
VALUES
('$first_name','$last_name','$email')
")) {
$success = 1;
$message = 'Customer ' . $first_name . ' successfully added!';
} else {
$success = 0;
$message = 'Something went wrong while adding the customer!';
}
print json_encode(array('success' => $success, 'message' => $message));
然后我们可能会使用 jQuery 处理这个表单的发送和从服务器接收数据,代码看起来有点像这样:
$(function() {
$('#add_customer_form').submit(function() { // handle form submit
var data = $(this).serialize(); // get form's data
var url = $(this).attr('action'); // get form's action
var method = $(this).attr('method'); // get form's method
$.ajax({
url: url, // where is this being sent to?
type: method, // we're performing a POST
data: data, // we're sending the form data
dataType: 'json', // what will the server send back?
success: function(data) { // the request succeeded, now what?
// here data is a JSON object we received from the server
// data.success will be 0 if something went wrong
// and 1 if everything went well. data.message will have
// the message we want to display to the user
// at this point you would use one of the techniques I linked
// to in order to display a fancy notification
// the line below will dynamically create a new div element,
// give it an ID of "message" (presumably for CSS purposes)
// and insert the message returned by the server inside of it
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error'); // to personalize the type of error
} else {
$div.addClass('success'); // to personalize the type of error
}
$('body').append($div); // add the div to the document
}
});
return false; // prevent non-ajax form submission.
});
});
我没有测试过任何代码,但想法就在那里。您从服务器返回带有数据的格式 JSON,并处理请求完成时 jQuery 触发的成功回调,并向您的文档添加一个您可以根据需要设置样式的元素(并显示 fadeIn() if你想要的)带有描述发生了什么的消息。您可能还需要捕获错误回调(如果您的服务器由于某种原因没有响应,则会触发该回调)并在这种情况下触发另一个警报。