使用mobileFirst javascript适配器读取本地服务器.json文件 [英] Reading local server .json file with mobileFirst javascript adapter

查看:140
本文介绍了使用mobileFirst javascript适配器读取本地服务器.json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以从javascript http适配器读取.json文件(位于服务器中)? 我尝试了互联网上描述的许多方法,但是它们似乎不起作用,因为它们是为浏览器javascript编写的(我收到未定义XMLHttpRequest或未定义activeObject之类的错误.)

Is there any way that I can read a .json file (located in server) from a javascript http adapter? I tried a lot of methods described in the internet but they don't seem to work because they are made for browser javascript (I get errors like XMLHttpRequest is not defined or activeObject is not defined).

例如,我使用了它,但是它不起作用:

for example, I used this but it doesn't work:

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                return allText;
            }
        }
    }
    rawFile.send(null);
}  

有没有不使用Java就能做到这一点的方法?

Is there any way that I could do this without using java?

推荐答案

您可以使用Javascript读取文件,如下所示.

You can read a file with Javascript as shown below.

function readFile(filename) {
    var content = "";

    var fileReader = new java.io.FileReader(filename);

    var bufferedReader = new java.io.BufferedReader(fileReader);

    var line;

    while((line = bufferedReader.readLine()) != null) {
        content += line;
    }   

    bufferedReader.close();

    return content;
}

function test() {
    var file = 'yourfilename.json';
    var fileContents;
    try {
         fileContents = JSON.parse(readFile(file));     
    }  catch(ex) {
        // handle error                
    }

    return  {
        fileContents: fileContents
    };
}

这篇关于使用mobileFirst javascript适配器读取本地服务器.json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆