我在Symfony3中实现了ExceptionListener
(也可以在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;
}
exceptionListener.php(partial)
# 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()));
}
使用香草ajax时,您需要将以下标头传递给您的ajax请求
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');