1
votes

everything goes well in a regular HTML page, but with the same code used in a liferay portlet,I have this problem:

GET http://localhost:8080/web/guest/data/myfile.json 404 (Not Found) index.js:103

This is the code:

function loadFiles(){

    loadJSONNetworkInventory(function(response) {

        parsedMyFile = JSON.parse(response);

    });
}


function loadJSONNetworkInventory(callback) {   

    var xobjNI = new XMLHttpRequest();
    xobjNI.overrideMimeType("application/json");
    xobjNI.open('GET', 'data/myfile.json', false); 
    xobjNI.onreadystatechange = function () {
        if (xobjNI.readyState == 4 && xobjNI.status == "200") {
            callback(xobjNI.responseText);
        }
    };
    xobjNI.send(null);  
}
2
Did you try using <%=request.getContextPath()%>/data/myfile.json?SASM
Yes, but this is the error: GET localhost:8080/web/guest/%3C%=request.getContextPath()%%3E/data/… 400 (Bad Request) index.js:103Heisenberg
First create a data folder at the root of your portlet, place your JSON file there then use this path /data/myfile.json.Parkash Kumar
Complete URL should be like http://localhost:8080/your-portlet/data/myfile.jsonParkash Kumar
Thank you, using the entire url it works.Heisenberg

2 Answers

1
votes

I am not sure, how do you assume that the URL http://localhost:8080/web/guest/data/myfile.json will serve you myfile.json as response when called. Where do you construct that URL and how do you suppose it to work?

Well, the other simple way around is that you create the data folder under the docroot of your portlet and move your myfile.json file there.

Now just above the include of your external javascript file (of which you have shared some code), add following lines:

<script type="text/javascript">
    var portletContextPath = '<%=request.getContextPath() %>';
</script>

And make following changes in your given script:

function loadJSONNetworkInventory(callback) {
    var xobjNI = new XMLHttpRequest();
    xobjNI.overrideMimeType("application/json");
    var jsonFilePath = portletContextPath + '/data/myfile.json';
    xobjNI.open('GET', jsonFilePath, false); 
    xobjNI.onreadystatechange = function () {
        if (xobjNI.readyState == 4 && xobjNI.status == "200") {
            callback(xobjNI.responseText);
        }
    };

    xobjNI.send(null);
}

That's it! portletContextPath will be serving as javascript variable to get dynamic context path of your portlet and jsonFilePath will be the path of your myfile.json.

0
votes

Try this on web.config

<system.webServer>
 <staticContent>
  <mimeMap  fileExtension=".json" mimeType="text/json" />
 </staticContent>
</system.webServer>