1

I am trying to access json API and retrieve some data for example : title , category, and images.

The problem is I cant get the source of the images.

I have tried :

  • field_image[0].src
  • field_image[0].getAttribute('src')
  • field_image[0].attr('src')
  • etc ..

but nothing worked correctly, it gives me "function not found" or "undefined".

pls help .. and thanks..

this is example of one json object that I retrieved.

Object
    body:"this is a normal text"
    field_category:"myCat"
    field_image:Array[2]
    0:
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/2017-01-19-photo-00000063.jpg?itok=g4DouHqQ" width="750" height="407" alt="" />"
    1:
    "<img typeof="foaf:Image" src="http://rs.ksu.edu.sa/sites/rs.ksu.edu.sa/files/styles/750x407/public/20150817-img_0604.jpg?itok=zNXuoh5t" width="750" height="407" alt="" />"

    length:2
    __proto__:
    Array[0]
    field_issue:"1260"
    field_page_number:"19"
    field_sub_title:"sub"
    field_sub_title1:
    Array[0]
    field_sub_title2:
    Array[0]
    nid:"1269"
    title:"<a href="/issue-1260/1269">this is title</a>"
    __proto__:
raedshari
  • 403
  • 5
  • 16

2 Answers2

3

Use JQuery:

var url = $(field_image[0]).attr('src');

This will parse the HTML string for you so you can access the attributes easily.

Andrew Monks
  • 656
  • 4
  • 11
1

thanks for @Andrew Monks. He provided me this link https://stackoverflow.com/questions/494143 where I found the solutin.

and here is the final solution:

I declared an attribute:

element: HTMLImageElement;

then I create this function that take html string and return the img src:

getImgSrc(htmlString){
    var div = document.createElement('div');
    div.innerHTML = htmlString;
    this.element = <HTMLImageElement>div.firstChild;
    return this.element.src;
}

and I called it here:

{{this.getImgSrc(item.field_image[0])}}
Community
  • 1
  • 1
raedshari
  • 403
  • 5
  • 16