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

时间:2015-11-04 15:14:27

标签: javascript php ajax post

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

这是代码的流程......

我在这样的页面上使用变量:

$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);
}

注意:使用&#39; GET&#39;发送此数据没有问题。方法,但然后一条长消息被切断。我还尝试设置数据&#39;我在过去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正在工作,POST =在ajaxRequest的另一端没有收到任何数据但是请求的其余部分返回了预期的内容。服务器请求中缺少的$ _POST数据是目前唯一无法使用此代码解决的问题。

看起来请求没有正确发送,但我无法确定原因。这是Chrome中NETWORK标签的截图:

3 个答案:

答案 0 :(得分:2)

问题是nginx发布的重定向(301),因为URL末尾缺少斜杠。这导致POST请求更改为GET。

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

开始讨论的旧方法:

您的问题似乎是您在整个数据字符串中包装的encodeURIComponent()函数。这取代了&amp;带有&amp;值的符号。如果您在浏览器开发人员控制台中对此进行调试,则会发现它在请求中未被识别为表单数据。你应该只是逃避你正在填写的变量。

顺便说一下:使用GET时这也应该有问题。

答案 1 :(得分:1)

这或多或少是我尝试过的,它是通过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'} } );

答案 2 :(得分:0)

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

我正在使用'/ Modules / AlertLayer'并更改为'/ Modules / AlertLayer /'修复了问题!