I facing problems when I'm trying to fetch data from Servlet. When I call the servlet by:
function urlFetchRequest(str, body = null, RequestType = 'GET'){
try
{
asyncRequest = new XMLHttpRequest();
asyncRequest.addEventListener("readystatechange", stateChange, false);
asyncRequest.open(RequestType, str, true); // /Test is url to Servlet!
asyncRequest.send(body);
}
catch(exception)
{
alert("Request failed");
}
}
I get back the information I need from the Servlet, and can use it by:
jsonRes = JSON.parse(asyncRequest.responseText)
which is work. My problem is when I need to pass data to the servlet. so I try to do it with fetch() since I have read that I can use JSON objects to the servlet (Again, I cannot use any javascript libraries such as jquery) and I can't use the data that the servlet returns. It getting "undefined".
The javascript scope that I using:
function newFetch(url, options){
fetch(url, options).then(async (res) => {
if(res.ok){
jsonRes = res.
if(theSurvey === null) {
surveyLength = Object.keys(jsonRes).length;
theSurvey = jsonRes;
}
}
});
}
I call it from here:
returnedObject.SurveyLoader = async () => {
//urlFetchRequest("/SurveyServlet");
//await SurveyResults();
newFetch("/SurveyServlet", {
method: "GET",
headers: headers,
})
}
My servlet is:
@WebServlet(name = "SurveyServlet", urlPatterns = {"/SurveyServlet"} )
public class SurveyServlet extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger("SurveyServlet");
private BufferedReader m_reader;
private String m_line;
public String convertWithStream(Map<String, String> map) {
String mapAsString = map.keySet().stream()
.map(key -> '\"' + key + '\"' + ":" + '\"' + map.get(key) + '\"')
.collect(Collectors.joining(", ", "{", "}"));
return mapAsString;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> SurveyObj = new LinkedHashMap<>();
m_reader = new BufferedReader(new FileReader(getServletContext().getRealPath("/poll.txt")));
m_line = m_reader.readLine();
SurveyObj.put(Integer.toString(0), m_line);
int id = 1;
while((m_line = m_reader.readLine())!=null) {
SurveyObj.put(Integer.toString(id), m_line);
++id;
}
String str = convertWithStream(SurveyObj);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//request.setAttribute("ArraySize", id);
// getServletContext().getRequestDispatcher("ResultServlet").forward(request,response);
PrintWriter out = response.getWriter();
out.write(str);
out.flush();
out.close();
}
}
My question here is about the fetch method. I know it gets Objects from a REST API. how do I use it to pass and get data from the servlet? how do I use the data I send to the servlet? If it's not possible, how do I use XMLHttpRequest to pass data to the servlet? (no $ use)
Thanks.