Тема: Json request using custom search api

Hi,

I have been trying to get this code to work but nothing happens. (There is too much information in the Json result)

All i want is the titles and links to be showned when executed.

<p id="demo"></p>
<p id="demo2"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
 
      for (x in myObj.link) {
       // var currentip =
       document.getElementById("demo").innerHTML = myObj.items.title;
       document.getElementById("demo2").innerHTML = myObj.items.link;
} 
    }
};
xmlhttp.open("GET", "https://www.googleapis.com/customsearch/v1?key=AIzaSyBuR2Oz3LCECz6SQy5ZOiJn7hZ2aIj_-S0&cx=007669213920302805361:-gvonkprlrq&q=bikes&alt=json", true);
xmlhttp.send();
</script>

Thanks

2

Re: Json request using custom search api

let me guess

myObj.link[x].items.title

UPD.
one more thing. you should define x by using var statement. It's global variable in your case.

3

Re: Json request using custom search api

I made a little mistake...

for (x in myObj.items)

And using your code...

myObj.items[x].title
myObj.items[x].link

Now how do i loop the results to show all available content instead of only showing the first result?

4

Re: Json request using custom search api

here you go

for (var x=0;x<myObj.items.length; x++) {
    // var currentip =
    document.getElementById("demo").innerHTML = myObj.items[x].title;
    document.getElementById("demo2").innerHTML = myObj.items[x].link;
}
Подякували: FakiNyan, leofun012

5

Re: Json request using custom search api

Thanks

Подякували: mike1

6

Re: Json request using custom search api

You could also do it like this

for (let item of myObj.items) {
        // var currentip =
        document.getElementById("demo").innerHTML = item.title;
        document.getElementById("demo2").innerHTML = item.link;
    }
Подякували: mike, leofun012