Theo Strauss
Theo Strauss

Reputation: 1351

Using jQuery and Ajax to access JSON file

I'm fairly new to JS. Right now, I have a JSON file on my Express server. Here is how I did that:

const data = require('./src/data.json')


app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.json(data);
});

Now, I need to access the dictionaries in that JSON file to use the text throughout my web app. I know I need to use Ajax and jQuery, but I'd love some explanation of how I could do that efficiently and easily. Here's a snippet of my JSON:

[{
    "name": "Il Brigante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-0.png"
}, {
    "name": "Giardino Doro Ristorante",
    "rating": "5.0",
    "match": "87",
    "cuisine": "Italian",
    "imageUrl": "/image-1.png"
}]

Any help would be immensely appreciated.

Upvotes: 0

Views: 2715

Answers (1)

Azat Akmyradov
Azat Akmyradov

Reputation: 176

You can use $.ajax function:

$.ajax({
   dataType: "json",
   url: 'url here',
   data: data,
   success(response) {
      console.log(response);
   }
});

Or use shorthand for that:

$.getJSON('url here', function(response) {
   console.log(response);
});

Either one is fine

Upvotes: 2

Related Questions