无法使用 Slim Framework 3 接收来自 AJAX POST 请求的响应


unable to receive response from ajax post request using slim framework 3

编辑:

该问题已得到纠正。ajax 请求的本地主机地址应该是 127.0.0.1 而不是 121.0.0.1


在我的客户端上,我有以下代码来请求在本地主机/登录名上开机

<html>
<title> Welcome </title>
<script>
function makeRequestObject(){
   var xmlhttp=false;
   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;
}
function showdata()
{
   var xmlhttp=makeRequestObject();
   var user=document.getElementById('user_name').value;
   var pass=document.getElementById('password').value;
   var url = 'https://121.0.0.1/login';  // invalid ip address for localhost
   var params = 'uname='+user+'&'+'pass='+pass;
   xmlhttp.open('POST', url, true);
   xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status == 200) {
         var content = xmlhttp.responseText;
         if( content ){
            document.getElementById('userdiv').innerHTML = content;
         }
      }
   }
   xmlhttp.send(params);
}
</script>
<body>
Enter user name : <input type="text" id="user_name" /><br/>
Enter your password : <input type="text" id="password"/><br/>
<input type="button" onclick="showdata()" value="Submit"><br/><br/>
<div id="userdiv">
</div>
</body>
</html>

我的服务器端有以下纤细的处理程序功能:

$app->post('/login', function () use ($app){
        $req = $app->request();
        $uname = $req->params('uname');
        $pass = $req->params('pass');
        $app->response()->header('Content-Type', 'application/json');
        echo json_encode($uname);
        exit;
});

我的问题是,当在服务器上看到请求时,对服务器进行了ajax调用。但是没有从服务器返回任何响应。

以下是Chrome开发人员工具中发生的事情的屏幕截图

http://s29.postimg.org/5379a7rt3/image.png

我可以看到对本地主机的初始调用正在工作但是下一个 Ajax 登录调用不起作用,因为只生成请求但没有收到响应。响应随后超时

我认为您的请求应该在 GET 方法中,而不是在上述情况下的帖子中。尝试更改为在 GET 而不是 post 中执行此请求。