Ajax返回var与服务器响应

时间:2012-04-03 17:55:14

标签: javascript ajax request response

我有这个功能,只需向服务器发出一个简单的请求,简单地说就是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 个答案:

答案 0 :(得分:1)

替换

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

if(ajax.readyState == 4) { 
          yourfunction(ajax.responseText);
}
[...]
function yourfunction(var response) {
      //use variable response here
}

答案 1 :(得分:0)

您可以使用responseText

访问回复
var response = ajax.responseText