Symfony 3-以XmlHttpRequest()(javascript)发送AJAX请求不会在后端以XmlHttpRequest的形式接收请求

Mag*_*ity 0 javascript ajax jquery xmlhttprequest symfony

ExceptionListener在Symfony3中有一个实现(也可以在Symfony2中使用)。在ExceptionListener识别该请求是否是正常的HTTP或AJAX(XmlHttpRequest的),并相应地产生响应。使用jQuery .post()或时.ajax()ExceptionListener返回$request->isXmlHttpRequest()为TRUE,但是使用javascript时var xhr = new XmlHTTPRequest()ExceptionListener返回$request->isXmlHttpRequest()为FALSE。我在需要通过AJAX上传文件的少量实例中使用后者(无法使用.post()或来完成).ajax()

我正在寻找解决方案(前端或后端)以解决我ExceptionListener错误地将其作为普通HTTP请求的问题。

前端代码:

function saveUser()
{
    var form = document.getElementById('userForm');
    var formData = new FormData(form);
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '{{url('saveUser')}}', true);
    xhr.onreadystatechange = function (node) 
    {  
        if (xhr.readyState === 4) 
        {  
            if (xhr.status === 200) 
            {  
                var data = JSON.parse(xhr.responseText);
                if (typeof(data.error) != 'undefined')
                {
                    $('#processing').modal('hide');
                    $('#errorMsg').html(data.error);
                    $('#pageError').modal('show');

                }
                else
                {
                    $('#successMsg').html('User Successfully Saved');
                    $('#processing').modal('hide');
                    $('#pageSuccess').modal('show');
                    $('#userModal').modal('hide');
                    updateTable();
                }
            } 
            else 
            {  
                console.log("Error", xhr.statusText);  
            }  
        }  
    };
    $('#processing').modal('show');
    xhr.send(formData);

    return false;
}
Run Code Online (Sandbox Code Playgroud)

ExceptionListener.php(部分)

# If AJAX request, do not show error page.
if ($request->isXmlHttpRequest())  # THIS RETURNS FALSE ON JS XmlHTTPRequest()
{
    $response = new Response(json_encode(array('error' => 'An internal server error has occured. Our development team has been notified and will investigate this issue as a matter of priority.')));
}
else
{       
    $response = new Response($templating->render('Exceptions/error500.html.twig', array()));
}
Run Code Online (Sandbox Code Playgroud)

mad*_*scu 5

使用香草ajax时,您需要将以下标头传递给您的ajax请求

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,添加请求头解决了问题。 (2认同)