从AJAX调用获取JSON对象

我是AJAXjavascript新手。 在我的项目中,我必须在我的javascript文件中获取一个json对象。 我使用了spray-json ,它向我显示了url中的json对象。 http://localhost:8081/all-modules

 { "status": "S1000", "description": "Success", "results": ["module1", "module2", "module3"] } 

我的Ajax电话

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert(data) }, success: function(data){ alert(data) } 

它返回一个警告[object Object] 。 这里有什么问题?

尝试以下方法;

 var data = '{"name": "John","age": 30}'; var json = JSON.parse(data); alert(json["name"]); alert(json.name); 

您还可以查看以下链接: 如何在JavaScript中访问JSON对象

如果您希望查看JSON对象中的所有数据,请使用JSON.stringify有关详细信息,请参阅此处

希望有所帮助。

只需console.log(数据),您将看到您的对象。

您可以通过类似的方式访问您的价值

 data.id //will give you id 

它也取决于你json你是如何创建检查这个解释

 // if it simply json then access it directly //Example => {"id":1,"value":"APPLE"} data.id; // will give you 1 // if it json array then you need to iterate over array and then get value. //Example => [{"id":1,"value":"APPLE"},{"id":2,"value":"MANGO"}] then data[0].id; // will give you 1 

所以你的代码将是这样的

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert(data.status);// S1000 alert(data.description);// Success // for results you have to iterate because it is an array var len = data.results.length; for(var i=0;i 

尝试console.log()它将登录控制台。 警报不显示该对象。

  $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ console.log(data) }, success: function(data){ console.log(data) } 

我想你只是打印对象。尝试这样的东西

 $.ajax({ url: 'http://localhost:8081/all-modules', dataType: 'application/json', complete: function(data){ alert("status = "+data.status+"descripttion"+data.description); }, success: function(data){ alert("status = "+data.status+"descripttion"+data.description); } 

data不再是JSON格式,它是一个Javascript对象 。 您不再需要使用jQuery.parseJSON之类的函数。

对于初学者来说,这是一个常见的错误。

如果你想看到这个Javascript对象,请尝试alert(JSON.stringify(data));

试试data[0].status; 。 您的数据现在位于对象中。 在console.log(data)您可以看到