简体   繁体   English

如何在 DIV 中显示来自 JSON 响应的错误?

[英]How to display errors from JSON response in a DIV?

I have an AJAX form to change password, I want to display all the validation errors in a HTML DIV.我有一个 AJAX 表单来更改密码,我想在 HTML DIV 中显示所有验证错误。

Below is my code, it's working fine to submit the form, but I can't pass the errors to the DIV, I keep getting: [object Object] .下面是我的代码,提交表单工作正常,但我无法将错误传递给 DIV,我不断收到: [object Object]

var url = "/posts/editProfile"; // the script where you handle the form input.

$.ajax({
       type: "POST",
       url: url,
       data: $("#profileForm").serialize(), // serializes the form's elements.
       success: function(data)
       {

           alert(data); // show response from the php script.

       },

       error: function(data)
       {

        console.log(data);

        $("#response").text(data);

       }

     });

e.preventDefault(); 

});

<div id="response"> <!-- output here --> </div>

Here's a screenshot of the response I got in the Console.这是我在控制台中得到的响应的屏幕截图。 截屏

This is because you are trying to set the inner text of a div element by simply passing the error object that's why you are getting [object Object] I'd suggest you examine your error object in debug mode, or by simply printing it as you did actually, and instead of doing这是因为您试图通过简单地传递错误对象来设置 div 元素的内部文本,这就是为什么您获得 [object Object] 我建议您在调试模式下检查您的错误对象,或者简单地打印它实际上做了,而不是做

$("#response").text(data);

do something like做类似的事情

$("#response").text(data.responseJSON.responseText);

But that will simply dump some error text within the DIV, i guess you want to show some meaningful validation to your users, to achieve this simply use your error object to display proper data whichever way it suits you best.但这只会在 DIV 中转储一些错误文本,我想您想向您的用户显示一些有意义的验证,要实现这一点,只需使用您的错误对象以最适合您的方式显示正确的数据。

this question is about more than three years, and until now no answer, I find it, but I'm sure you have found a solution to this problem.这个问题大概三年多了,到现在都没有答案,我找到了,但是我相信你已经找到了解决这个问题的方法。 this easy way, my solution is:这个简单的方法,我的解决方案是:

error: function(error)
{
    // this Error is an Object
    var errors = error.responseJSON.errors;
    // Loop this object and pring Key or value or both
    for (const [key, value] of Object.entries(errors)) {
         console.log(`${key}: ${value}`);
    }
 }

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

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