Ajax返回带有服务器响应的var

Ajax return var with server response

本文关键字:响应 var 服务器 返回 Ajax      更新时间:2023-09-26

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

因为我想单独处理响应。

有人能帮我吗?

更换

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

带有

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

您可以使用responseText 访问响应

var response = ajax.responseText