简体   繁体   English

将数组分配给URL中的JSON数据

[英]Assigning array to JSON data in URL

I'm trying to assign a JSON array from a URL to a variable. 我正在尝试将URL的JSON数组分配给变量。 Here's my code: 这是我的代码:

$.getJSON("tljson.json",function(result){
  var items = [];
  items.push(result);
});

However, 'alerting' the items only returns 但是,“更改”项目只会返回

[object Object],[object Object],[object Object],[object Object]

What am I doing wrong? 我究竟做错了什么?

What you're doing wrong is alerting the result. 您做错了,正在警告结果。 You have an array of four objects, but alert only shows the default text representation of objects, [object Object] . 您有四个对象组成的数组,但是alert仅显示对象的默认文本表示形式[object Object] Convert your data to string yourself before printing. 在打印之前将数据转换为字符串。 For example, instead of alert(result) , you can try alert(JSON.stringify(result)) . 例如,可以代替alert(result)来尝试alert(JSON.stringify(result))

Also, alert is ugly, annoying and hard to use; 另外, alert是丑陋的,令人讨厌的并且难以使用。 if you can, use console.log() and its friends instead, much easier on the programmer. 如果可以,请改用console.log()及其朋友,这对程序员来说要容易得多。 Check the results in the JavaScript console. 在JavaScript控制台中检查结果。 (This is under the assumption the alert() was for your own debugging benefit; if it's for users, try doing something in HTML instead.) (这是在假定alert()是为了您自己的调试收益的前提下;如果是为了用户的,请尝试使用HTML代替。)

它已经是一个变量, result是json响应,您可以像将其推送到项目中一样访问该响应。

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

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