How to load json in jquery from file using regex?

Viewed 57

I have json files which contain epoch time in file's name. Like this one

apple1623781928.json
banana1623781928.json

How can I load those json since the name is random, I hope I can find solution like using kind of "*" for neglecting the number or something, like this:

var fruit = "apple";
$.getJSON('fruit'+'(*)'.json, function (result) {
    console.log(result);
}

I'm just using JQuery and VanillaJs for this project. Anyone could you help me please? Thanks a bunch.

1 Answers

It's not possible, unless you make a request to every single possible path to see what the response is (not feasible), or unless the server provides the information. Without knowing a working path, you cannot request a sort of wildcard path like you're looking for, unless the server explicitly has logic set up to allow such a thing.

You will need to change the server files or the server configuration to either send the random filenames that are available to the client on pageload, or to provide a route that will parse the request URL (which could include a * as a wildcard) and use that as a base to search through the server folders to see if a matching file exists. This would have to be implemented in server-side code like Node.js or PHP.

This is a pretty odd sort of problem to be having, though. If I were you, think more about why you have such files, and how and when they need to be served to clients, and figure out a different approach to allow the client to consume them.

Related