簡體   English   中英

沒有jQuery的AJAX不會將POST數據發送到PHP文件

[英]AJAX without jQuery is not sending POST data to PHP file

我一直試圖讓一個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);
}

注意:使用'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正在工作,POST =在ajaxRequest的另一端沒有收到任何數據但是請求的其余部分返回了預期的內容。 服務器請求中缺少的$ _POST數據是目前唯一無法用此代碼解決的問題。

看起來請求沒有正確發送,但我無法確定原因。 這是chrome中NETWORK選項卡的屏幕截圖:

問題是nginx發布的重定向(301),因為URL末尾缺少斜杠。 這導致POST請求更改為GET。

技術細節: https//softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect


開始討論的舊方法:

您的問題似乎是您在整個數據字符串中包裝的encodeURIComponent()函數。 這取代&符號&amp; 值。 如果您在瀏覽器開發人員控制台中對此進行調試,您將看到它在請求中未被識別為表單數據。 你應該只逃避你正在填寫的變量。

順便說一句:當你使用GET時,這也應該是有問題的。

這或多或少是我嘗試過的,它是通過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 test/ /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'} } );

當調用ajaxRequest時,url必須在url的末尾有一個“/”(例如,如果你沒有指定/index.php文件)。

我使用'/ Modules / AlertLayer'並更改為'/ Modules / AlertLayer /'修復了問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM