简体   繁体   中英

Get a JSON API response using vanilla javascript

I'd like to use wikipedia search api from javascript, I know it might be easier with something like jquery but I'd like to get a good grip on the basics before using frameworks. Here is the code I wrote, but I never get the alert:

document.getElementById("go_search").addEventListener("click", () => {
    let wiki = new XMLHttpRequest();
    wiki.addEventListener("load", () => {
      alert(wiki.responseText)
    });
    wiki.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Albert+Einstein");
    wiki.send();

  })

The wikipedia adress is a search Albert Einstein, which is just to test if the code is working. Thanks for your help it is much appreciated!

Add origin=* to the URL query params to make JSON API requests to Wikipedia.

Change your request URL to

https://en.wikipedia.org/w/api.php?origin=*&action=query&format=json&list=search&utf8=1&srsearch=Albert+Einstein

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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