C
C
CJDmitry2019-08-20 06:04:25
ASP.NET
CJDmitry, 2019-08-20 06:04:25

XMLHttpRequest in received response not working JS?

Hello!
There is a site on ASP Net CORE. Wrote an AJAX function to get a partial view that has JS in the body. Everything loads fine, but the script doesn't work, why? Although earlier the request was made through jquery and everything worked like clockwork. But for the sake of one function I do not want to use the library. Why doesn't js work in response and how to fix it?
Here is my function:

function commentNewShow() {
        var formData = new FormData();
        formData.append('Url', '@url');
        formData.append('UrlName', '@title');

        var xhr = new XMLHttpRequest();
        xhr.open("POST", '/Comments/NewForm', true);
        xhr.send(formData);

        xhr.onreadystatechange = function (e) {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var commentNew = document.getElementById('commentNew');
                    commentNew.innerHTML = xhr.responseText;
                } else {
                    alert('Возникла ошибка. Попробуйте позже.');
                }
            }
        };
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vgbege, 2019-08-20
@cjdmitri

in jq, somewhere inside, eval () is called,
like they did something like this

commentNew.innerHTML = xhr.responseText;
var scripts = commentNew.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
    eval(scripts[i].innerText);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question