Search code examples
javascriptjqueryajaxuwpwinjs

Load all images from folder: winjs uwp app


I am using javascript (winJS) for making my windows store app (UWP app). I want to load all svg images from my app directory and show them inside a div. I was able to do this using ajax request. But looks like ajax doesnt works in winJS UWP app. I used jquery and ajax request like this:

var fileextension = ".svg";
var classx = "image";
var tr = "true";

var businessDir = "image/business";
$.ajax({
    url: businessDir,
    success: function (data) {
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location.host, "").replace("http:///", "");

            $(".myDiv").append($("<img src=" + filename + " class=" + classx + " draggable=" + tr + "></img>"));

        });
    }
});

How can load images from my 'image/buisness' directory in winJS UWP app.I also tried this code in cordova windows store app, but that also didnt work.


Solution

  • But looks like ajax doesnt works in winJS UWP app

    Firstly, ajax is supported in UWP app, but there are a few things you need to notice, details please reference this thread. But although jQuery.ajax() can be used in a UWP app, you cannot make a AJAX call to a local resource as the request is made using HTTP. For details about this please reference this thread.

    How can load images from my 'image/buisness' directory in winJS UWP app

    According to your scenario, you need to load images from local directory, so that you cannot use AJAX call. You can just use the file operation relative APIs in UWP to load the images, for example, Storage​Folder and StorageFile classes. More details about how to do please reference this article and this official sample. Here is a demo for loading images from the "images/bussiness" directory in WinJs UWP app you may reference:

    function addimage() { 
        var classx = "image";
        var tr = "true";
        var root = Windows.ApplicationModel.Package.current.installedLocation.path;
        var path = root + "\\images\\business";
        var StorageFolder = Windows.Storage.StorageFolder;
        var folderPromise = StorageFolder.getFolderFromPathAsync(path);
        folderPromise.done(function getFolderSuccess(folder) {
            var filesInFolderPromise = folder.getFilesAsync();
            filesInFolderPromise.done(function getFilesSuccess(filesInFolder) {
                filesInFolder.forEach(function forEachFile(item) {             
                    if (item.name.includes("svg")) {
                        var img = document.createElement("img");
                        img.src = "images/business/" + item.name;
                        document.getElementById("myDiv").appendChild(img);
                    }
                });
            });
        });
    }