M
M
Max1005002015-01-08 22:31:23
JavaScript
Max100500, 2015-01-08 22:31:23

Ajax in a dynamically linked script, how to do?

There is an index.html file in which a javascript file with ajax is dynamically connected. That is:
INDEX.HTML

<!DOCTYPE HTML>
<html>

<head>
  <title>Untitled</title>
  <script>
var js = document.createElement('script');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', 'script1.js');
  js.setAttribute('defer', 'defer');
  document.getElementsByTagName('HEAD')[0].appendChild(js);
  </script>
</head>
<body>
</body>
</html>

SCRIPT1.JS
function getXmlHttp(){
  var xmlhttp;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

// javascript-код голосования из примера
function vote() {
  // (1) создать объект для запроса к серверу
  var req = getXmlHttp()

        // (2)
  // span рядом с кнопкой
  // в нем будем отображать ход выполнения
  //var statusElem = document.getElementById('vote_status')

  req.onreadystatechange = function() {
        // onreadystatechange активируется при получении ответа сервера

    if (req.readyState == 4) {
            // если запрос закончил выполняться
            //alert("4444");
      //statusElem.innerHTML = req.statusText
            // показать статус (Not Found, ОК..)

      if(req.status == 200) {
                 // если статус 200 (ОК) - выдать ответ пользователю
        alert("Ответ сервера: "+req.responseText);
      }
      // тут можно добавить else с обработкой ошибок запроса
    }

  }

       // (3) задать адрес подключения
  req.open('GET', 'http://javascript.ru/ajax/intro', true);

  // объект запроса подготовлен: указан адрес и создана функция onreadystatechange
  // для обработки ответа сервера

        // (4)
  req.send(null);  // отослать запрос

        // (5)
  //statusElem.innerHTML = 'Ожидаю ответа сервера...'
}
vote();

If you statically connect the script1.js file on the index.html page, then everything will work and the response will contain the page code. How to do advise? It turns out that if the file is located on the same domain as the script, then it is executed normally, but if it is on a different domain, then it is impossible to read the page, that is, to make a get request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey P, 2015-01-09
@ruddy22

instead of JSONP, I would suggest using CORS , because not only receiving data is supported, but also sending.
may be useful in the future

V
Vladislav, 2015-01-08
Kozulya @5angel

The problem is with the cross domain request. More about the subject .
In this case, since you need exactly get, you can solve the problem using jsonp. Again, there is a link in the article above .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question