Php 通过POST发送jQuery.serialize表单,需要控制器的JSON响应

Php 通过POST发送jQuery.serialize表单,需要控制器的JSON响应,php,jquery,ajax,json,cakephp-2.0,Php,Jquery,Ajax,Json,Cakephp 2.0,我想问您,我如何发送带有jQuery表单序列化的ajax请求并从控制器接收JSON响应?我一直在尝试许多解决方案,但没有一个对我有效。在那件事上我有点经验 你能举个好例子吗?谢谢大家! 通过AJAX使用序列化表单(post)发送post 在控制器函数中处理操作,并在ajax->success中获得JSON响应 我使用的是CakePHP2.4.1 我的ajax请求 $.ajax({ type: "post", url: location.pathname

我想问您,我如何发送带有jQuery表单序列化的ajax请求并从控制器接收JSON响应?我一直在尝试许多解决方案,但没有一个对我有效。在那件事上我有点经验

你能举个好例子吗?谢谢大家!

  • 通过AJAX使用序列化表单(post)发送post
  • 在控制器函数中处理操作,并在ajax->success中获得JSON响应
  • 我使用的是CakePHP2.4.1


    我的ajax请求

           $.ajax({
           type: "post",
           url: location.pathname + "/edit",
           data: data,
           success: function(response) {
                $("#content").html(response); // i would like to recieve JSON response
                alert(response);              // here ;C
    
           },
           error: function(){        
                    alert("error");
           }
           });
    

    我在控制器中的部分功能

          public function admin_edit(){
            //................ some logic passed 
            if($this->request->is('ajax')){
            $this->layout = 'ajax';
            $this->autoRender = false;
            $this->set(compact('user'));
            $this->disableCache();
            foreach($this->request->data['User'] as $key => $value){
                if(empty($value)){
                    unset($this->request->data['User'][$key]);
                }
            }
            $this->User->id = $this->request->data['User']['id'];
            if($this->User->save($this->request->data)){
                $this->Session->setFlash('Użytkownik został zmodyfikowany');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Nie zmodyfikowano użytkownika');
            }
          }
    
      public function admin_edit(){
        //................ some logic passed 
        if($this->request->is('ajax')){
            /* layout not necessary if you have autoRender = false */
            //$this->layout = 'ajax';
            /* actually, no need for this either with _serialize, but add it if you have unwanted html rendering problems */
            //$this->autoRender = false;
    
            $this->set(compact('user'));
    
            /* other code that doesn't really matter for the example ... */
    
            $this->User->id = $this->request->data['User']['id'];
            if($this->User->save($this->request->data)){
               /* NO!! */
               //$this->Session->setFlash('Użytkownik został zmodyfikowany');
               //return $this->redirect(array('action' => 'index'));
    
               $status = 'OK';
               $message = 'Użytkownik został zmodyfikowany';
               $this->set(compact('message', 'status'));
            }
            /* NO EITHER!! */
            //$this->Session->setFlash('Nie zmodyfikowano użytkownika');
               $status = 'NOT-OK';
               $message = 'Not sure what your flash says but let\'s assume it an error alert';
               $this->set(compact('message', 'status'));
    
            //serialize variables you have set for the "ghost" view
            $this->set('_serialize', array('user', 'message', 'status'));
        }
      }
    

    我想要接收的是来自控制器的JSON响应。 范例

    这里有一个例子

    示例:发布到test.php页面并获取以json格式返回的内容

    因此,插入ajax调用类似于:

    $.post( "test.php", data, function(response) {
                $("#content").html(response); 
                alert(response);              
    
           }, "json");
    

    编辑:如果您没有得到正确的响应,请显示响应或返回json的php代码。它不在您提供的函数中。

    好的,我认为让您困惑的是一些小东西,但对于经验不足的人来说,混合在一起可能有点难以调试。我将发布一个基本的示例,说明什么应该对您有效,然后您将对其进行迭代。告诉我们是否有其他错误(检查特定错误比检查视图/控制器可能的错误更容易)

    首先,在ajax调用中,更改
    console.log(响应)以更好地调试

        //alert(response);
        console.log(response);
    },
    error: function(){        
        alert("error");
        console.log(response);
    }
    });
    
    在控制器中

          public function admin_edit(){
            //................ some logic passed 
            if($this->request->is('ajax')){
            $this->layout = 'ajax';
            $this->autoRender = false;
            $this->set(compact('user'));
            $this->disableCache();
            foreach($this->request->data['User'] as $key => $value){
                if(empty($value)){
                    unset($this->request->data['User'][$key]);
                }
            }
            $this->User->id = $this->request->data['User']['id'];
            if($this->User->save($this->request->data)){
                $this->Session->setFlash('Użytkownik został zmodyfikowany');
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash('Nie zmodyfikowano użytkownika');
            }
          }
    
      public function admin_edit(){
        //................ some logic passed 
        if($this->request->is('ajax')){
            /* layout not necessary if you have autoRender = false */
            //$this->layout = 'ajax';
            /* actually, no need for this either with _serialize, but add it if you have unwanted html rendering problems */
            //$this->autoRender = false;
    
            $this->set(compact('user'));
    
            /* other code that doesn't really matter for the example ... */
    
            $this->User->id = $this->request->data['User']['id'];
            if($this->User->save($this->request->data)){
               /* NO!! */
               //$this->Session->setFlash('Użytkownik został zmodyfikowany');
               //return $this->redirect(array('action' => 'index'));
    
               $status = 'OK';
               $message = 'Użytkownik został zmodyfikowany';
               $this->set(compact('message', 'status'));
            }
            /* NO EITHER!! */
            //$this->Session->setFlash('Nie zmodyfikowano użytkownika');
               $status = 'NOT-OK';
               $message = 'Not sure what your flash says but let\'s assume it an error alert';
               $this->set(compact('message', 'status'));
    
            //serialize variables you have set for the "ghost" view
            $this->set('_serialize', array('user', 'message', 'status'));
        }
      }
    
    我认为你的主要缺陷是返回重定向。这是json的禁忌。您所做的是为ajax调用提供索引操作的html。这毫无意义。如果希望操作返回JSON,那么所有案例都必须返回JSON,而不是html。因此,没有
    setFlash
    ,没有
    重定向
    。我通常在这里做的是返回带有状态和消息的JSON数据(如上面的代码所示)。然后,在ajax调用中,在成功时,解析JSON数据,读取状态,如果确定,则重定向(通过js),如果不确定,则显示得到的错误消息

    希望它能帮你把事情弄清楚


    [微小编辑]:
    json\u encode
    也可以,但是在CakePHP中,做CakePHP(ians?)所做的()(因为你不需要回显变量)。

    你试过使用(例如
    $this->set(“'u serialize',array('posts');
    )?是的,但它没有起作用:(出现了什么错误?
    .html(response)
    警报(响应)
    只会在服务器端代码正常工作的情况下给您
    [object object]
    [object object,object object]
    。@Kevin B返回HTML代码,而不是[object][object]Nunser我会马上检查它。我和您的示例一样,但console.log中的响应为空:(忘记在那里包括状态和消息…让我更正一下…那里。仍然得到空响应?(我刚刚更改了最后一行)是的,仍然是空的响应。但是,如果我使用echo json_encode,那么就可以了,但是我想使用Cake Way确保您已经注释了
    autoRender=false
    layout=ajax
    。而且,Cake的行为有点奇怪,字符不是标准字符,因此出于调试目的,请使用“香草”的信。按照你的建议做了,还是空的
      public function admin_edit(){
        //................ some logic passed 
        if($this->request->is('ajax')){
            /* layout not necessary if you have autoRender = false */
            //$this->layout = 'ajax';
            /* actually, no need for this either with _serialize, but add it if you have unwanted html rendering problems */
            //$this->autoRender = false;
    
            $this->set(compact('user'));
    
            /* other code that doesn't really matter for the example ... */
    
            $this->User->id = $this->request->data['User']['id'];
            if($this->User->save($this->request->data)){
               /* NO!! */
               //$this->Session->setFlash('Użytkownik został zmodyfikowany');
               //return $this->redirect(array('action' => 'index'));
    
               $status = 'OK';
               $message = 'Użytkownik został zmodyfikowany';
               $this->set(compact('message', 'status'));
            }
            /* NO EITHER!! */
            //$this->Session->setFlash('Nie zmodyfikowano użytkownika');
               $status = 'NOT-OK';
               $message = 'Not sure what your flash says but let\'s assume it an error alert';
               $this->set(compact('message', 'status'));
    
            //serialize variables you have set for the "ghost" view
            $this->set('_serialize', array('user', 'message', 'status'));
        }
      }