没有jQuery的AJAX不发送POST数据到PHP文件

问题描述:

我一直在试图让一个ajax警报层使用POST方法几天,我不能想出它不工作的原因。我使用相同的基本代码通过ajax在其他管理页面上通过POST发送表单数据,但是当我尝试发送不是来自表单的数据时,没有任何内容到达$ _POST中的服务器。没有jQuery的AJAX不发送POST数据到PHP文件

下面的代码流...

我喜欢使用这些页面上的变量:

$alertLayer = 1; 
$autoCloseAlertLayer = 1; 
$addAlertLayerCloseButton = 1; 
$alertLayerMessage = $alertLayerMessage . '<h1>Test</h1><p>3rd test of the alert layer module.</p>'; 
$redirect = 0; 
$redirectTo = 0; 

,我包括在这样的页面的底部调用一个函数的脚本:

if ($alertLayer == true) 
{ 
    echo "<script type='text/javascript' id='alertLayerScript'>Lib.ajaxAlertFunction('/Modules/AlertLayer', $autoCloseAlertLayer, $addAlertLayerCloseButton, '$alertLayerMessage', $redirect, '$redirectTo');</script>"; 
} 

下面是被调用脚本:

Lib.ajaxAlertFunction = function (senturl, autoClose, closeButton, message, redirect, redirectTo) 
{ 
var ajaxRequest; 

try 
{ 
    ajaxRequest = new XMLHttpRequest(); 
} 
catch (e) 
{ 
    try 
    { 
     ajaxRequest = new ActiveXObjext("Msxml2.XMLHTTP"); 
    } 
    catch (e) 
    { 
     try 
     { 
      ajaxRequest = new ActiveXObjext("Microsoft.XMLHTTP"); 
     } 
     catch (e) 
     { 
      alert ("Your browser can't handle the truth!"); 
      return false; 
     } 
    } 
} 

if (!senturl) 
{ 
    return false; 
} 
else 
{ 

    // var data = "autoClose=" + encodeURIComponent(autoClose) + "&closeButton=" + encodeURIComponent(closeButton) + "&message=" + encodeURIComponent(message) + "&redirect=" + encodeURIComponent(redirect) + "&redirectTo=" + encodeURIComponent(redirectTo); 
    // var data = encodeURIComponent("autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo); 
    var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo; 
} 

ajaxRequest.onreadystatechange = function() 
{ 
    if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) 
    { 
     document.getElementById('outerFrame').innerHTML += ajaxRequest.responseText; 

     newAlertLayer = document.getElementById('alertLayer'); 
     var arr = newAlertLayer.getElementsByTagName('script') 
     for (var n = 0; n < arr.length; n++) 
     { 
      eval(arr[n].innerHTML) 
     } 
    } 
} 
ajaxRequest.open('POST', senturl, true); 
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
ajaxRequest.send(data); 
} 

注意:使用'GET'方法发送此数据时没有问题,但是长消息会被截断。我也试着用几种不同的方法来设置'数据'变量,这些方法在过去的3天里我搜索得不成功。

一个期望$ _ POST数据的代码去如下:

<?php 
$ROOT = $_SERVER['DOCUMENT_ROOT']; 
?> 
<div id="alertLayer"> 
<link rel="stylesheet" href="<?php $ROOT ?>/Modules/AlertLayer/alertLayer.css"> 
<script src="/Modules/AlertLayer/alertLayer.js"></script> 
<div id="alertBlock"> 
<?php 
foreach ($_POST as $key => $value) 
{ 
    echo "<p>" . $key . " = " . $value . "</p>"; 
} 
foreach ($_GET as $key => $value) 
{ 
    echo "<p>" . $key . " = " . $value . "</p>"; 
} 
?> 
</div> 
</div> 

我缺少什么?与使用POST发送表单数据和发送变量以相同的方式连接有什么不同? 同样,当我将数据添加到url字符串但GET不足时,GET正在工作,POST =在ajaxRequest的另一端收到的数据完全没有收到,但剩下的请求完全返回预期的结果。服务器请求中缺少的$ _POST数据是目前我无法使用此代码解决的唯一问题。

看起来好像没有正确发送请求,但我无法确定原因。以下是Chrome浏览器中NETWORK选项卡的屏幕截图:

+0

尝试从数据中删除'encodeURIComponent' ....就像你说的那样,它会被截断 - 没有它看起来很好。 – RamRaider

+0

我刚刚编辑上面的代码,以显示我最初开始尝试像encodeURIComponent和其他之前开始。使用字符串连接在一起就是我的问题开始,我猜为什么我没有问题,使用GET。 – FolioGraphic

问题是由于URL末尾缺少斜线而导致nginx发出重定向(301)。这导致POST请求被更改为GET。

技术细节:https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect


启动该讨论的老办法:

您的问题似乎是,你周围的整个数据包串的encodeURIComponent()功能。这将用&amp;值代替&标志。如果您在浏览器开发人员控制台中进行调试,您会发现它在请求中未被识别为表单数据。你应该只逃避你填写的变量。

btw:当你使用GET时,这也应该是有问题的。

+0

谢谢,我应该覆盖更多我以前的工作。使用encodeURICompenent()是我尝试使其工作的最后努力之一。我开始使用现在编辑并显示在上面的代码中的字符串。如果一切看起来没问题,我应该看看哪些事情/条件(服务器设置等)可能导致此问题? – FolioGraphic

+0

当我发出警报(数据) autoClose = 1&closeButton = 1&message =

测试

警报层模块的第三个测试。

&redirect = 0&redirectTo = 0 我使用这一行代替发送GET(并且它工作)。 ajaxRequest.open(“GET”,senturl +“?”+ data,true); – FolioGraphic
+0

你有没有在encodeURIComponent()变量中转义你的值?不是整个字符串。但是你得到的每一个变量都会放入你的函数中。 – heine

这或多或少是我尝试过的,它通过POST发送数据。

window.onload=function(){ 
     Lib.ajaxAlertFunction('/test/target.php', 0, 0, 'Fantastic - data is being sent via POST! Amazeballs!', 0, 0); 
    }; 



    var Lib={}; /* Because I don't have the rest of `Lib` at my disposal */ 
    Lib.ajaxAlertFunction = function (senturl, autoClose, closeButton, message, redirect, redirectTo) { 
     var ajax;/* renamed only for brevity */ 
     try { 
      ajax = new XMLHttpRequest(); 
     } catch (e) { 
      try { 
       ajax = new ActiveXObjext("Msxml2.XMLHTTP"); 
      } catch (e) { 
       try { 
        ajax = new ActiveXObjext("Microsoft.XMLHTTP"); 
       } catch (e) { 
        alert ("Your browser can't handle the truth!"); 
        return false; 
       } 
      } 
     } 

     if (!senturl) return false; 
     else { 
      var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo; 
     } 


     ajax.onreadystatechange = function() { 

      if(ajax.readyState == 4 && ajax.status == 200) { 
       /* 
       document.getElementById('outerFrame').innerHTML += ajax.responseText; 
       newAlertLayer = document.getElementById('alertLayer'); 
       var arr = newAlertLayer.getElementsByTagName('script') 
       for (var n = 0; n < arr.length; n++) { 
        eval(arr[n].innerHTML); 
       } 
       */ 

       console.log(ajax.responseText); 
      } 
     } 
     ajax.open('POST', senturl, true); 
     ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
     ajax.send(data); 
    } 

对于测试的缘故,/test/target.php很干脆:

<?php 
    exit(print_r($_POST,true)); 
?> 

和响应:

Array 
(
    [autoClose] => 0 
    [closeButton] => 0 
    [message] => Fantastic - data is being sent via POST! Amazeballs! 
    [redirect] => 0 
    [redirectTo] => 0 
) 

如果有帮助的任何,这里是一个基本的AJAX功能,我使用测试,可能有些东西可能有用吗?

 function _ajax(url, options){ 
      var factories=[ 
       function() { return new XMLHttpRequest(); }, 
       function() { return new ActiveXObject('Msxml2.XMLHTTP'); }, 
       function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); }, 
       function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); }, 
       function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); }, 
       function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); }, 
       function() { return new ActiveXObject('Microsoft.XMLHTTP'); } 
      ]; 
      /* Try each factory until we have a winner */ 
      for(var i=0; i < factories.length; i++) { 
       try { var req = factories[ i ](); if(req!=null) { break; } } 
       catch(err) { continue; } 
      }; 

      var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST'; 
      var callback=options.hasOwnProperty('callback') ? options.callback :false; 

      if(!callback){ 
       alert('No callback function assigned - a callback is required to handle the response data'); 
       return false; 
      } 

      var headers={ 
       'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8", 
       'Content-type': 'application/x-www-form-urlencoded', 
       'X-Requested-With': 'XMLHttpRequest' 
      }; 

      /* The main parameters of the request */ 
      var params=[]; 
      if(options.hasOwnProperty('params') && typeof(options.params)=='object'){ 
       for(var n in options.params) params.push(n + '=' + options.params[n]); 
      } 

      /* Additional arguments that can be passed to the callback function */ 
      var args=options.hasOwnProperty('args') ? options.args : options; 

      /* Assign callback to handle response */ 
      req.onreadystatechange=function(){ 
       if(req.readyState==4) { 
        if(req.status==200) options.callback.call(this, req.response, args); 
        else console.warn('Error: '+req.status+' status code returned'); 
       } 
      } 

      /* Execute the request according to desired method */ 
      switch(method){ 
       case 'POST': 
        req.open(method, url, true); 
        for(header in headers) req.setRequestHeader(header, headers[ header ]); 
        req.send(params.join('&')); 
       break; 
       case 'GET': 
        req.open(method, url+'?'+params.join('&'), true); 
        for(header in headers) req.setRequestHeader(header, headers[ header ]); 
        req.send(null); 
       break; 
      } 
     } 



/* to use */ 
_ajax.call(this, '/test/target.php',{ callback:console.info, method:'post',params:{'field':'value','field2':'value2'} }); 
+0

感谢您的持续帮助,我将使用您的示例来尝试解决这个问题,但如果你已经拿到我的代码并证明它可行,那么我认为我在别处忽略了一个问题,但我不知道如何追踪它。 – FolioGraphic

+0

在你认为错误可能蔓延并观察输出的各个点上使用'console.log'。 – RamRaider

当调用ajaxRequest URL必须有一个“/”在URL的末尾(如果你不指定例如一个的index.php文件)。

我正在使用'/ Modules/AlertLayer'并更改为'/ Modules/AlertLayer /'已解决此问题!