D
D
Dizzabel2019-12-02 12:22:27
JSON
Dizzabel, 2019-12-02 12:22:27

Where is the error or what am I doing wrong?

There is a JSON request in the form of a url

var newArr = JSON.parse(req.responseText);
  }
  catch (e) {
    document.getElementById("PRVDATA").innerHTML = "Ошибка разбора ответа от сервера: " + e +"<br>" +req.responseText;
  }

The answer comes, but, in the answer there are double quotes, from this the answer crashes. I added it to escape quotes (and other things), but for some reason it doesn't work. Tell me where am I wrong?
function escapeHtmlChars(req) {
    return req
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
for (var i = 0; i < newArr.length; i++) {
    newArr[i].correct = escapeHtmlChars(newArr[i].correct);
    for (var j = 0; j < newArr[i].choices.length; j++) {
        newArr[i].choices[j] = escapeHtmlChars(newArr[i].choices[j]);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2019-12-05
@vabka

Perhaps you did not receive json in the response, but some other text. For example, if you are not authorized, then some services may redirect to the authorization page, and then the json parser dies. Try using fetch
instead of JSON.parse

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question