【问题标题】:404 Not Found JSON file Liferay404 未找到 JSON 文件 Liferay
【发布时间】:2016-03-14 09:43:15
【问题描述】:

在普通的 HTML 页面中一切正常,但是在 liferay portlet 中使用相同的代码,我遇到了这个问题:

GET http://localhost:8080/web/guest/data/myfile.json 404(未找到)index.js:103

这是代码:

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);  
}

【问题讨论】:

  • 您是否尝试过使用<%=request.getContextPath()%>/data/myfile.json
  • 是的,但这是错误:GET localhost:8080/web/guest/%3C%=request.getContextPath()%%3E/data/… 400 (Bad Request) index.js:103
  • 首先在您的portlet 的根目录下创建一个data 文件夹,将您的JSON 文件放在那里,然后使用此路径/data/myfile.json
  • 完整的 URL 应该像 http://localhost:8080/your-portlet/data/myfile.json
  • 谢谢你,使用它的整个网址。

标签: javascript json liferay


【解决方案1】:

我不确定,你如何假设 URL http://localhost:8080/web/guest/data/myfile.json将为您服务 myfile.json 作为调用时的响应。您在哪里构建该 URL 你认为它是如何工作的?

好吧,另一种简单的方法是在 portlet 的 docroot 下创建 data 文件夹,然后将 myfile.json 文件移到那里。

现在在您的外部 javascript 文件(您已共享一些代码)的包含上方,添加以下行:

<script type="text/javascript">
    var portletContextPath = '<%=request.getContextPath() %>';
</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);
}

就是这样! portletContextPath 将用作 javascript 变量以获取您的 portlet 的动态上下文路径,jsonFilePath 将是您的 myfile.json 的路径。

【讨论】:

  • 谢谢,首先感谢您的解释.. 正常工作的 url 是 localhost:8080/portlet-name/data/myfile.json",正如我在上面写的,而不是 @987654321 @正如你所写..它们是不同的,实际上第二个不起作用..
  • 所以,离开顶部,按照建议做。 var jsonFilePath = portletContextPath + '/data/myfile.json'; 将与 /portlet-name/data/myfile.json 完全相同
【解决方案2】:

在 web.config 上试试这个

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

【讨论】:

    猜你喜欢
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2020-06-10
    • 1970-01-01
    • 2014-11-10
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多