【发布时间】:2017-02-20 20:40:45
【问题描述】:
我在 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(部分)
# 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()));
}
【问题讨论】:
-
您是否尝试过检查 $_SERVER['HTTP_X_REQUESTED_WITH']?
-
$_SERVER['HTTP_X_REQUESTED_WITH'] 在 .post() 和 .ajax() 上返回 'XmlHTTPRequest' - 正常 HTTP 请求和 javascript new XmlHTTPRequest() 上的“未定义索引” - 所以同样的问题(无法区分 new XmltHttpRequest() 实际上是一个 AJAX 请求)。
-
然后在使用 vanilla ajax 时将 X-Requested-With 标头传递给您的 ajaxed 页面
-
@sakhunzai 您的回复是零帮助
-
为什么不通过 jquery $.ajax 函数发送文件?
标签: javascript jquery ajax xmlhttprequest symfony