Dojo xhr get not setting XmlHttpRequest


Dojo xhr get not setting XmlHttpRequest

我正在使用Dojo1.7.2,并尝试使用以下代码

var request = xhr.get({
        url: location,
        content : content,
        load : function( data ){
            for( var x in data )
                {
                    alert ( x + data[x] );
                }
        },
        error : function()
        {
            alert( 'Had an eror' );
        },
        handleAs : 'json'
    });

然后在php中,我执行以下操作,尝试检测xmlhttprequest

function isAjax(){
    $ajax = (isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) ) &&
        ( strtolower( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) ==  'xmlhttprequest' );
    return $ajax;
}

但是isAjax函数返回false。

如果我做xhr.post,那么它工作得很好。我认为这只是使用GET而不是POST的副作用?是这样,还是其他我没有检查的东西。

此解决方案基于Zend Framework版本。

function isAjax() {
    $header = 'X_REQUESTED_WITH';
    // Try to get it from the $_SERVER array first
    $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header));
    if (isset($_SERVER[$temp])) {
        return $_SERVER[$temp] == 'XMLHttpRequest';
    }
    // This seems to be the only way to get the Authorization header on
    // Apache
    if (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
        if (isset($headers[$header])) {
            return $headers[$header]  == 'XMLHttpRequest';
        }
        $header = strtolower($header);
        foreach ($headers as $key => $value) {
            if (strtolower($key) == $header) {
                return true;
            }
        }
    }
    return false;
}

附加此标头不是一种标准,因为在大多数情况下,这是一种非默认的开销。

你需要自己设置标题,并且可以随心所欲地称呼它。你想要的是headers: { "X-Requested-With": "XMLHttpRequest" }:

var request = xhr.get({
    url: location,
    content : content,
    headers: { "X-Requested-With": "XMLHttpRequest" }, // << < add this
    load : function( data ){
        for( var x in data )
            {
                alert ( x + data[x] );
            }
    },
    error : function()
    {
        alert( 'Had an eror' );
    },
    handleAs : 'json'
});