【问题标题】:Symfony2: JQuery request isn't XHRSymfony2:JQuery 请求不是 XHR
【发布时间】:2013-03-01 06:12:28
【问题描述】:

我正在使用 Symfony2 开发一个简单的博客应用程序。
我想通过 ajax 检查登录数据:

  • 如果数据正确 -> 转发到另一个页面
  • 如果不是 -> 以 400 状态响应并为表单设置动画

我的问题是 JQuery 发送的请求似乎不是 XHR。

HTML:

<form id="logfo" action="{{path('Login_Ajax')}}" method="POST">
    <p> Name </p>
    <input type="text" id="logname"> </br>
    <p> Password </p>
    <input type="text" id="logpass"> </br>
    <input type="submit" value="Log In">
</form>

Javascript:

$(document).ready(function() {
    //listen for the form beeing submitted
    $("#logfo").submit(function(){
        var url = $("#logfo").attr("action");
        //start the post
        $.post(url,{Name:$("#logname").val(),
            Password:$("#logpass").val()}, 
            function(data){
                if(data.responseCode==400) {
                    //animate the Form
                    var fo=$("#logfo");
                    fo.animate({left:'+=25px'}, "fast");
                    fo.animate({left:'-=50px'}, "fast");
                    fo.animate({left:'+=50px'}, "fast");
                    fo.animate({left:'-=25px'}, "fast");
                }
        });
    }); 
});

routing.yml:

Login_Ajax:
pattern: /thefitthing/logjax
defaults: {_controller: FitcompTheFitThingBlogBundle:Ajax:login }
requirements:
    _method:  POST

出于测试原因,我替换了用于将请求与数据进行比较的代码
使用简单的 if-terms 从数据库中获取。
控制器:

class AjaxController extends Controller {

    public function logInAction()
    {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) { 
            $name=$request->request->get('Name');
            if($name == "page") return new Response("",400);
            if($name == "plant") return $this->redirect($this->generateUrl('Thanks_Page'));
        }
        else return $this->render('FitcompTheFitThingBlogBundle:Blog:test.html.twig', array('hint' => "noXHR"));
    }
}

【问题讨论】:

    标签: jquery ajax symfony xmlhttprequest


    【解决方案1】:

    您的submit 处理程序不会阻止浏览器提交表单,因此您的 XHR 请求永远没有机会完成(浏览器只是先进行常规 POST)。您可以通过简单地删除您的 $.post 电话来确认这一点 - 行为完全没有区别。

    通过阻止默认操作来解决此问题:

    $("#logfo").submit(function(event) {
        event.preventDefault();
        $.post(...);
    });
    

    【讨论】:

    • 我改了,现在也不能提交表单
    • @Simeon:对不起,我不明白你的意思。请更具体。
    • 当我点击提交按钮时没有任何反应
    • @Simeon:检查浏览器的 Javascript 控制台是否有错误。 XHR 应该被发送,但响应处理程序可能有问题?
    • 我拼错了一些东西……抱歉,来晚了。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2020-10-28
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多