问题
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);
}
Is there any way that I could do this without using java?
回答1:
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
};
}
回答2:
For those interested in using Java.
One thing you can do is create a Javascript adapter which will use Java code. It is pretty simple to set up.
First create a Javascript adapter.
Then create a Java class under the server/lib
folder. I created the class ReadJSON.java
under the package com.sample.customcode
.
Inside the ReadJSON.java
public class ReadJSON {
public static String readJSON() throws IOException {
//Open File
File file = new File("file.txt");
BufferedReader reader = null;
try {
//Create the file reader
reader = new BufferedReader(new FileReader(file));
String text = null;
//read file
while ((text = reader.readLine()) != null) {}
} finally {
try {
//Close the stream
reader.close();
}
}
return "the text from file";
}
}
Inside your javascript adapter you can use Java methods like below:
function readJOSN() {
var JSONfromServer = com.sample.customcode.ReadJSON.readJSON();
return {
result: JSONfromServer
};
}
Hope this helps.
来源:https://stackoverflow.com/questions/37414618/reading-local-server-json-file-with-mobilefirst-javascript-adapter