如何解决[object Object] Javascript错误?

时间:2019-06-29 04:43:26

标签: javascript html ajax methods get

我想显示来自JSON占位符的请求。我不确定从哪里开始,甚至不确定要解决我的错误的正确问题是什么。

我了解为什么会发生错误,如下所示(what does [object Object] mean?)我不知道如何解决该问题。我知道我需要使用console.log(),但不确定如何将特定值返回到变量,然后在屏幕上显示它。

HTML

<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>

JavaScript

$(document).ready(function(){
  $("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos/1", function(title, completed){
      alert("Title: " + title + "\nCompleted: " + completed);
    });
  });
});

预期结果

  "Title": "delectus aut autem",
  "completed": success

2 个答案:

答案 0 :(得分:2)

标题 是一个对象,它不是您正在考虑的属性。您必须从 title object 中访问 title 属性。

尝试title.title

$(document).ready(function(){
  $("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos/1", function(title, completed){
      alert("Title: " + title.title + "\nCompleted: " + completed);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>

答案 1 :(得分:1)

您可以在https://jsonplaceholder.typicode.com/上查看示例。这表明它返回对象而不是单个值。示例如下所示:

$(document).ready(function(){
  $(document).on('click','.btn', function(){
   $.get("https://jsonplaceholder.typicode.com/todos/1", function(result_object, completed){
     console.log(result_object);
     alert("Title: " + result_object.title + "\nCompleted: " + completed);
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" class="btn btn-dark">Click here to execute your first Ajax get request</button>