【问题标题】:unable to receive response from ajax post request using slim framework 3 [closed]无法使用苗条框架 3 接收来自 ajax 发布请求的响应 [关闭]
【发布时间】:2015-01-23 23:14:47
【问题描述】:

编辑:

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


在我的客户端上,我有以下代码可以在 localhost/login 上请求 POST

<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

我可以看到对 localhost 的初始调用正在运行 但是下一个 ajax 调用登录不起作用,因为只产生请求但没有收到响应。响应随后超时

【问题讨论】:

  • 请将 "content-type" 字符串替换为 "Content-type"
  • 试过了。这不是问题
  • 你记得在代码开头调用$app = new Slim();$app->run();在它的最后?
  • 其实我的代码结构很好。有一个 index.php 文件需要这个 postRoutes.php 文件和 getRoutes.php 文件。主 index.php 文件有新的 slim 实例和 app->run 方法。但是这个文件 postRoutes.php 仅包含与 底部一起显示的代码
  • 您好,请原谅我浪费您的时间。反正我不能原谅自己。问题是 localhost 是 127.0.0.1 而不是 121.0.0.1 .... 我纠正了这个问题,它现在可以工作了

标签: javascript php html ajax slim


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多