使用ajax从json中读取和显示值

时间:2022-12-04 19:04:35

Im trying to get data from a .json file that is recieved via post method to a external server, using ajax function and display it all on html (tags and data). I can get the json data and display it via console log, however im not able to iterate over it, or simply display in on the html side.

Im试图从.json文件中获取数据,该文件通过post方法接收到外部服务器,使用ajax函数并在html(标记和数据)上显示所有数据。我可以获得json数据并通过控制台日志显示它,但是我无法对其进行迭代,或者仅仅在html端显示。

I've tryed to create a public array and push the response to it, create a function, etc.. but looks like ajax function loads after it, and there's no data at all, then i've tried to concat a string with the values that i get on console, but no success.

我已经创建了一个公共数组并将响应推给它,创建一个函数等等。但是看起来ajax函数加载之后,根本就没有数据,然后我尝试将一个字符串与我在控制台得到的值连接起来,但是没有成功。

I can't even get the actual data, only the tags. Im a little bit confused here. Can some one help me?

我甚至不能得到实际的数据,只有标签。我有点糊涂了。有人能帮我吗?

Here's my code and what it displays on console.

这是我的代码以及它在控制台显示的内容。

component.hmt:

component.hmt:

<ul>
   <li>{{res}}</li>
</ul>

component.ts

component.ts

public res = "";
ngOnInit() {

let settings = {
          "async": true,
          "crossDomain": true,
          "url": "ip/to/api",
          "context": this,  //added this
          "method": "POST",
          "data": "\"dataApi\"",
      };

$.ajax(settings).done(function (response) {
console.log(response);
this.res = response; //added this
       for(let i in response)
       {
           //console.log(i);
           this.res += i + " - ";
           for(let j in response[i])
           {
               //console.log(j);
               this.res += j + " : \n ";
               for(let t in response[i][j])
               {
                   //console.log(t);
                   this.res += t +"\n";
               }
           }
       }
       console.log(this.res);
       return this.res;

   });
  }
}

Here's the output on console.log: the thing is that on console log i can get all the tags : data, but i can't never get the data on res string to display.

这是控制台的输出。日志:在控制台日志中,我可以得到所有的标记:数据,但是我不能永远不能显示res字符串的数据。

Console.log(response) : All the data i need to display.

日志(响应):我需要显示的所有数据。

this.res : the tags without any data.

这一点。雷斯:没有任何数据的标签。

使用ajax从json中读取和显示值

Thanks in advance!!

提前谢谢! !

Edit: Here's the output of {{res | json}} on html side:

编辑:这是html端{{{res | json}}的输出:

{ "Challenges": [ { "Challenge.Closed": false, "Challenge.EndSubmissionDate": "Sat Feb 13 00:00:00 GMT 2010", "Challenge.Title": "net.Partner", "Challenge.CompositeId": "Id=3_Tenant=103", "Challenge.Code": "2010/001"....

{“挑战”:“挑战”。封闭”:假的,”挑战。报名日期:“2010年2月13日星期六00:00 GMT”,“挑战”。标题:“净。合作伙伴”、“挑战。CompositeId”:“Id = 3 _tenant = 103”、“挑战。代码”:“2010/001”....

I have the json like text based..i want for example:

我有基于json的文本。我想举个例子:

Challenge.Closed : false
....
Idea.id: 4
...

and access some of the tags that i know that exists, like id.. Do i have to map it?

访问一些我知道存在的标签,比如id。我必须把它映射出来吗?

4 个解决方案

#1


1  

So i think i am close, i know that with {{res | json }} i can print all the data and tags, including curly braces etc from the json file. (its like a json file to text)

所以我想我已经接近了,我知道使用{res | json}我可以打印json文件中的所有数据和标签,包括花括号等等。(就像json文件到文本)

But i need to print only the entity: tags and values. keep in mind that i neves know what comes on the json file. Here's what i have so far:

但是我只需要打印实体:标记和值。请记住,我不知道json文件的内容。这是我目前所拥有的:

public entity = [];
public cont = [];

.Created and array and pushes all the entities:

.创建和排列并推动所有实体:

this.res = response;
for(let i in response)
{
   //array with entities inside json
   this.entity.push(i);
}
return this.res;

the on the html side i can get:

在html方面,我可以得到:

<!-- all the data from json-->
     <ng-container>
       <li>{{res}}</li>
     </ng-container>

<!-- all the Challenges or whatever comes after res --- res.HERE-->
      <ng-container>
        <li>{{res.Challenges | json}}</li>
      </ng-container>


<!-- or (example with Ideas)-->
      <ng-container *ngFor="let x of res.Ideas">
         <li>{{x | json}}</li>
      </ng-container>


<!-- print all the entities that come in the json 
(challenges, Ideas, whatever.. that goes with res.HERE)-->
       <ng-container *ngFor="let i of entity">
         <li>{{i}}</li>
       </ng-container>

so, i can get the entities, each entity has its own attributes, for example to entity Challenges:

因此,我可以得到实体,每个实体都有自己的属性,例如实体挑战:

Challenge.Closed
Challenge.EndSubmissionDate
Challenge.Title
etc..

but how can i acess the values to each attribute? with the html i've posted i can get what's inside the coments, so i could iterate each entity like:

但是,我如何为每个属性赋予值呢?通过我发布的html,我可以得到coments里面的内容,所以我可以迭代每个实体,比如:

<!-- json file has 2 entities -->
    <ng-container *ngFor="let i of entity">
        <!-- trying to print res.Challenges and res.Ideas -->
         <ng-container *ngFor="let jsn of res.i">
             <li>{{jsn | json}}</li>
         </ng-container>
    </ng-container>

but, no success. i don't see how can i solve it! with that for loop i've posted earlier:

但是,没有成功。我不知道怎么解出来!用我之前贴的for循环:

for(let i in response)
{
  this.cont.push(i);
    for(let j in response[i])
    {
      this.cont.push(j);
          for(let t in response[i][j])
          {
            this.cont.push(t);
          }
    }
}

I've printed on the html side:

我已经打印在html的一面:

使用ajax从json中读取和显示值

the best thing was to get the values for each "entity.attribute" and not only the tags like i have (showed on the image)

最好的方法是获取每个“实体”的值。属性,而不仅仅是像我这样的标签(如图所示)

#2


1  

A little closer to the solution, i've found the way to retrive the values, for example to entity Challenge:

更接近解决方案,我找到了方法来检索值,例如实体挑战:

this.responseList.Challenges["0"]["Challenge.Code"]

gives me the challenge code.

给我挑战代码。

But instead of challenge it can be whatever, that's the name of entity, for example Ideas:

但不是挑战它可以是任何东西,那是实体的名字,例如想法:

this.responseList.Ideas["0"]["Idea.Code"]

gives me the idea code.

给我一个想法代码。

if i want to know the names of each entity:

如果我想知道每个实体的名称:

this.responseList
 >{Challenges: Array(13), Ideas: Array(1)}

The test was made on console with a debugger in the 'for loop' inside the code that follows:

测试是在控制台进行的,在下面代码的“for loop”中有一个调试器:

html - Im just printing Challenges, but i neves knwo what entity i have.. it can me Ideas, or other..

我只是打印挑战,但我不知道我有什么实体。它可以是我的想法,或者其他的。

<ul *ngFor="let res of responseList.Challenges">
   <li> {{res | json}} </li>
</ul>

Component.ts

Component.ts

public entity = [];         //has the entity names ideias, challenges whatever...
public responseList = "";   //the json that comes from the server

ngOnInit() {

   let settings = {
       "async": true,
       "crossDomain": true,
       "url": "ip/to/api",
       "method": "POST",
       "data": "\"dataApi\"",
   };

   $.ajax(settings).done((rest) => this.response(rest));

}

 response(res){

this.responseList = res; //the json file with allt he information

      for(let i in res)
      {
         //array with all entities inside json
         this.entity.push(i);
      }

      debugger;
}

Based on that information, i have to work inside .ts with for loops and arrays and the just print the result on .html, right? Can somebody help me with that?

基于这些信息,我必须在。ts内部处理for循环和数组然后在。html上打印结果,对吧?谁能帮我一下吗?

Edited for solution

编辑的解决方案

If i could print the values on the console, i can print them too with my previous for loop:

如果我可以在控制台打印值,我也可以用之前的for循环打印它们:

component.ts: for(let i in res) { for(let j in res[i]) { this.singleArray.push({ tag: i, value: val });

组件。t: for(let i in res) {for(let j in res[i]) {this.singleArray。push({tag: i, value: val});

         for(let t in res[i][j])
         {    
             this.singleArray.push({
             tag: t,
             value: this.responseList[i][j][t]
         });

         if(t.split(".",2)[1] === "CompositeId")
         {
          this.singleArray.push({
          tag: "URL:",
          value: this.moduleName + "/" + t.split(".",2)[0] + "/" + this.responseList[i][j][t].match(/=(.*)_/)[1]
          });
        }
     }
   }
}

with that 'for loop' i can get the tag and the value: to print them on html side:

有了for循环,我就可以得到标签和值:在html端打印它们:

html

html

<ng-container *ngFor="let item of singleArray">
   <li>
     {{item.tag}} - {{item.value}}
   </li>
   <a *ngIf="item.tag.includes('URL')"> <a href="{{item.value}}"><li>- LINK -</li></a></a>
</ng-container>

#3


0  

You should use the $.ajax() context object here like:

您应该在这里使用$.ajax()上下文对象:

let settings = {
          "async": true,
          "crossDomain": true,
          "url": "ip/to/api",
          "context": this,
          "method": "POST",
          "data": "\"dataApi\"",
      };

#4


0  

try this:

试试这个:

all you have to do is to loop through response

你所要做的就是循环响应

.HTML

. html

<div  class="div1">
  <ul class="r " *ngFor="let res of responseList.challenges">
    <li>
     {{res.closed}} 
    </li>
  </ul>
</div>

.TS

.TS

public responseList = "";
ngOnInit() {

let settings = {
          "async": true,
          "crossDomain": true,
          "url": "ip/to/api",
          "method": "POST",
          "data": "\"dataApi\"",
      };

    $.ajax(settings).done() = (res) => this.response(res);

response(res){
    console.log(res);
      this.responseList = res;
    }

#1


1  

So i think i am close, i know that with {{res | json }} i can print all the data and tags, including curly braces etc from the json file. (its like a json file to text)

所以我想我已经接近了,我知道使用{res | json}我可以打印json文件中的所有数据和标签,包括花括号等等。(就像json文件到文本)

But i need to print only the entity: tags and values. keep in mind that i neves know what comes on the json file. Here's what i have so far:

但是我只需要打印实体:标记和值。请记住,我不知道json文件的内容。这是我目前所拥有的:

public entity = [];
public cont = [];

.Created and array and pushes all the entities:

.创建和排列并推动所有实体:

this.res = response;
for(let i in response)
{
   //array with entities inside json
   this.entity.push(i);
}
return this.res;

the on the html side i can get:

在html方面,我可以得到:

<!-- all the data from json-->
     <ng-container>
       <li>{{res}}</li>
     </ng-container>

<!-- all the Challenges or whatever comes after res --- res.HERE-->
      <ng-container>
        <li>{{res.Challenges | json}}</li>
      </ng-container>


<!-- or (example with Ideas)-->
      <ng-container *ngFor="let x of res.Ideas">
         <li>{{x | json}}</li>
      </ng-container>


<!-- print all the entities that come in the json 
(challenges, Ideas, whatever.. that goes with res.HERE)-->
       <ng-container *ngFor="let i of entity">
         <li>{{i}}</li>
       </ng-container>

so, i can get the entities, each entity has its own attributes, for example to entity Challenges:

因此,我可以得到实体,每个实体都有自己的属性,例如实体挑战:

Challenge.Closed
Challenge.EndSubmissionDate
Challenge.Title
etc..

but how can i acess the values to each attribute? with the html i've posted i can get what's inside the coments, so i could iterate each entity like:

但是,我如何为每个属性赋予值呢?通过我发布的html,我可以得到coments里面的内容,所以我可以迭代每个实体,比如:

<!-- json file has 2 entities -->
    <ng-container *ngFor="let i of entity">
        <!-- trying to print res.Challenges and res.Ideas -->
         <ng-container *ngFor="let jsn of res.i">
             <li>{{jsn | json}}</li>
         </ng-container>
    </ng-container>

but, no success. i don't see how can i solve it! with that for loop i've posted earlier:

但是,没有成功。我不知道怎么解出来!用我之前贴的for循环:

for(let i in response)
{
  this.cont.push(i);
    for(let j in response[i])
    {
      this.cont.push(j);
          for(let t in response[i][j])
          {
            this.cont.push(t);
          }
    }
}

I've printed on the html side:

我已经打印在html的一面:

使用ajax从json中读取和显示值

the best thing was to get the values for each "entity.attribute" and not only the tags like i have (showed on the image)

最好的方法是获取每个“实体”的值。属性,而不仅仅是像我这样的标签(如图所示)

#2


1  

A little closer to the solution, i've found the way to retrive the values, for example to entity Challenge:

更接近解决方案,我找到了方法来检索值,例如实体挑战:

this.responseList.Challenges["0"]["Challenge.Code"]

gives me the challenge code.

给我挑战代码。

But instead of challenge it can be whatever, that's the name of entity, for example Ideas:

但不是挑战它可以是任何东西,那是实体的名字,例如想法:

this.responseList.Ideas["0"]["Idea.Code"]

gives me the idea code.

给我一个想法代码。

if i want to know the names of each entity:

如果我想知道每个实体的名称:

this.responseList
 >{Challenges: Array(13), Ideas: Array(1)}

The test was made on console with a debugger in the 'for loop' inside the code that follows:

测试是在控制台进行的,在下面代码的“for loop”中有一个调试器:

html - Im just printing Challenges, but i neves knwo what entity i have.. it can me Ideas, or other..

我只是打印挑战,但我不知道我有什么实体。它可以是我的想法,或者其他的。

<ul *ngFor="let res of responseList.Challenges">
   <li> {{res | json}} </li>
</ul>

Component.ts

Component.ts

public entity = [];         //has the entity names ideias, challenges whatever...
public responseList = "";   //the json that comes from the server

ngOnInit() {

   let settings = {
       "async": true,
       "crossDomain": true,
       "url": "ip/to/api",
       "method": "POST",
       "data": "\"dataApi\"",
   };

   $.ajax(settings).done((rest) => this.response(rest));

}

 response(res){

this.responseList = res; //the json file with allt he information

      for(let i in res)
      {
         //array with all entities inside json
         this.entity.push(i);
      }

      debugger;
}

Based on that information, i have to work inside .ts with for loops and arrays and the just print the result on .html, right? Can somebody help me with that?

基于这些信息,我必须在。ts内部处理for循环和数组然后在。html上打印结果,对吧?谁能帮我一下吗?

Edited for solution

编辑的解决方案

If i could print the values on the console, i can print them too with my previous for loop:

如果我可以在控制台打印值,我也可以用之前的for循环打印它们:

component.ts: for(let i in res) { for(let j in res[i]) { this.singleArray.push({ tag: i, value: val });

组件。t: for(let i in res) {for(let j in res[i]) {this.singleArray。push({tag: i, value: val});

         for(let t in res[i][j])
         {    
             this.singleArray.push({
             tag: t,
             value: this.responseList[i][j][t]
         });

         if(t.split(".",2)[1] === "CompositeId")
         {
          this.singleArray.push({
          tag: "URL:",
          value: this.moduleName + "/" + t.split(".",2)[0] + "/" + this.responseList[i][j][t].match(/=(.*)_/)[1]
          });
        }
     }
   }
}

with that 'for loop' i can get the tag and the value: to print them on html side:

有了for循环,我就可以得到标签和值:在html端打印它们:

html

html

<ng-container *ngFor="let item of singleArray">
   <li>
     {{item.tag}} - {{item.value}}
   </li>
   <a *ngIf="item.tag.includes('URL')"> <a href="{{item.value}}"><li>- LINK -</li></a></a>
</ng-container>

#3


0  

You should use the $.ajax() context object here like:

您应该在这里使用$.ajax()上下文对象:

let settings = {
          "async": true,
          "crossDomain": true,
          "url": "ip/to/api",
          "context": this,
          "method": "POST",
          "data": "\"dataApi\"",
      };

#4


0  

try this:

试试这个:

all you have to do is to loop through response

你所要做的就是循环响应

.HTML

. html

<div  class="div1">
  <ul class="r " *ngFor="let res of responseList.challenges">
    <li>
     {{res.closed}} 
    </li>
  </ul>
</div>

.TS

.TS

public responseList = "";
ngOnInit() {

let settings = {
          "async": true,
          "crossDomain": true,
          "url": "ip/to/api",
          "method": "POST",
          "data": "\"dataApi\"",
      };

    $.ajax(settings).done() = (res) => this.response(res);

response(res){
    console.log(res);
      this.responseList = res;
    }