在ajax成功时显示用户消息

我试图在jquery / ajax响应时显示两种用户消息。

在我的处理脚本中,我存储这些消息,如下所示:

// Initialize Json array. $messages =''; // Check for the email: if (!empty($_POST['email'])) { $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $email = filter_var($email, FILTER_VALIDATE_EMAIL); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // Not a valid email $messages = array('success'=>false,'cssClass'=>'alert-danger','message'=>'Email does not match the required format.'); } // Print a message based upon the result: if ($stmt->affected_rows == 1) { // Print a message and wrap up: $messages = array('success'=>true,'cssClass'=>'alert-success','message'=>'Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the "Password Modification" link.'); } echo json_encode($messages); 

在Jquery中,我试图填充这样的消息。 但我无法打印出这些消息。

更新:

 success: function (json) { if (json.success) { // it worked alert('ok'); $('#message').append(''); $('#message').show(); } else { // something went wrong alert('not ok'); $('#message').append(''); $('#message').show(); } 

谁能告诉我哪里出错了? 希望有人可以帮助我。

谢谢。

你只是缺少一行代码。

服务器脚本提供的是JSON 字符串

并且您无法从JSON 字符串访问属性。

您必须首先解析JSON 字符串并从中创建一个JSON 对象

 success: function (jsonString) { var json = JSON.parse(jsonString); //parse the JSON string and create JSON object if (json.success) { // it worked alert('ok'); $('#message').append(''); $('#message').show(); } else { // something went wrong alert('not ok'); } } 

上面的代码使用JS Platform提供的JSON

在返回数据上使用parseJSON :

 if (json) { json = $.parseJSON(json); alert(json.success); }