dongqiao5573 2018-02-17 20:29
浏览 179

获得$ request-> isXmlHttpRequest()始终为false

i want to persist an entity and catch a message with ajax (without Jquery), but i got troubles with boolean $request->isXmlHttpRequest() .

The script here :

var xhr = getXMLHttpRequest(); 

xhr.open("POST", "{{ path('deplacement') }}", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("coordonnee="+abs+"-"+ord+"&name="+personnage[0].getAttribute('id'));

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        var classPersonnage = personnage[0].getAttribute('class');
        var arrayClassPersonnage = classPersonnage.split(' ');
        var id = personnage[0].getAttribute('id');
        personnage[0].removeAttribute('class');
        var newClass= '';
        for (i=0; i < arrayClassPersonnage.length-1; i++){
            newClass= newClass+' '+arrayClassPersonnage[i];
        }
        document.getElementById(id).setAttribute('class', newClass);
        var resultat = JSON.parse(xhr.responseText);
        alert(resultat['message']);
    }

My controller php here

/**
 * @Route("/game/combat/test", name="deplacement")

 */
public function deplacementAction(Request $request){

    if($request->isXmlHttpRequest())
    {
        $response = new JsonResponse();         
        return $response->setData(array('message' => 'Ok.'));
    }
    else{
        $response = new JsonResponse();         
        return $response->setData(array('message' => 'false'));
    }
}

I got always 'false'. I tried to do this :

$response = new JsonResponse();
return $response->setData(array('message' => 'Ok.'));

So without $request->isXmlHttpRequest(), but i catch a internal error server 500. Please help me, i become crazy.

  • 写回答

2条回答 默认 最新

  • douyi1944 2018-02-18 07:53
    关注

    Checking what a method does looking at its code is always helpful to find solutions to your code issues. If you check isXmlHttpRequest method you can see in its dockblock something like this:

    It works if your JavaScript library sets an X-Requested-With HTTP header

    And method body is:

    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
    

    Then you need to add the right header (which is added by default by most JS frameworks/libraries, for example see jQuery scrolling to headers section):

    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题