Ajax возвращает var с ответом сервера - PullRequest
0 голосов
/ 03 апреля 2012

У меня есть эта функция, просто сделайте простой запрос к серверу, просто AJAX.

( function() {
'use strict';
Request  = { 
    Call: function ( u, theme, params ) { 
      var ajax, t; ajax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); 
      ajax.onreadystatechange = function() { 
        if ( ajax.readyState == 4 ) { 
          this.Reponse = ajax.responseText; 
        } 
      }; 
      if ( theme == 'POST' ) { 
        ajax.open('POST', u, true); 
        ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded'); 
        ajax.send(params); 
      } 
      else { 
        if ( theme == 'GET' ) { 
          ajax.open('GET', u, true); 
          ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
          ajax.send(null); 
        }  
      } 
    },
    Response : null
  } 
})();

Я хочу сохранить ответ сервера в переменную, например:

window.onLoad = function () {
  Request.call('post.php', 'POST', 'bar=foo');
  //then
  document.getElementById('foo').innerHTML = Ajax.Request.Response;
}

Потому что я хочу обработать ответ отдельно.

Кто-нибудь может мне помочь?

Ответы [ 2 ]

1 голос
/ 03 апреля 2012

Заменить

if ( ajax.readyState == 4 ) { 
          this.Reponse = ajax.responseText; 
        } 

на

if(ajax.readyState == 4) { 
          yourfunction(ajax.responseText);
}
[...]
function yourfunction(var response) {
      //use variable response here
}
0 голосов
/ 03 апреля 2012

Вы можете получить доступ к ответу, используя responseText

var response = ajax.responseText
...