【问题标题】:Sending jQuery.serialize form via POST, expecting JSON response from controller通过 POST 发送 jQuery.serialize 表单,期望来自控制器的 JSON 响应
【发布时间】:2013-12-11 19:16:42
【问题描述】:

我想问你如何发送 ajax 请求并通过 jQuery 表单序列化并从控制器接收 JSON 响应?我一直在尝试很多解决方案,但没有一个对我有用。我在这方面有一点经验。

你能举个很好的例子吗?谢谢!

  1. 通过 AJAX 以序列化形式 (POST) 发送帖子
  2. 在控制器函数中处理动作并在 ajax 中获取 JSON 响应 -> 成功

我使用的是 CakePHP 2.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');
        }
      }

我想收到来自控制器的 JSON 响应。 例子

  [{"id":"1", "username":"test", ... }]

【问题讨论】:

  • 您是否尝试过使用serialize(例如$this->set('_serialize', array('posts'));)?
  • 是的,但没有成功:(
  • 它给出了什么错误?
  • 如果服务器端代码正常工作,.html(response)alert(response) 只会给你[object Object][object Object,object Object]
  • @Kevin B 返回 HTML 代码,而不是 [object][object] Nunser 我会马上检查它

标签: php jquery ajax json cakephp-2.0


【解决方案1】:

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

首先,在ajax调用中,将console.log(response);改成更好的调试方式

    //alert(response);
    console.log(response);
},
error: function(){        
    alert("error");
    console.log(response);
}
});

在控制器中

  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,没有redirect。我通常在这里做的是返回带有状态和消息的 JSON 数据(如上面的代码)。然后,在 ajax 调用中,如果成功,您会解析 JSON 数据,读取状态,如果成功则重定向(通过 js),如果没有,则显示您收到的错误消息。

希望它为您解决问题。

[微小的编辑]:json_encode 也可以,但是在 CakePHP 中,做 CakePHP(ians?) 做的事情 (serialize)(因为你不需要回显变量)。

【讨论】:

  • 我在你的例子中做了,但我在 console.log 中有空响应:(
  • 忘记在此处包含状态和消息...让我更正一下...那里。仍然得到空洞的回应? (我刚改了最后一行)
  • 是的,仍然是空的响应。但是,如果我使用 echo json_encode 就可以了,但是我想使用 Cake 方式
  • 确保您已评论 autoRender = falselayout = ajax。此外,cake 对非标准字符的行为有点奇怪,因此出于调试目的,将消息更改为带有“香草”字母的简单内容。
  • 按照你的建议做了,仍然是空的
【解决方案2】:

JQuery.com有一个例子

例子:发布到test.php页面,获取已经返回json格式的内容

 <?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>

.

$.post( location.pathname + "/edit", data, function( data ) {
  console.log( data.name ); // John
  console.log( data.time ); // 2pm
}, "json");

所以插入 ajax 调用类似于:

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

       }, "json");

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

【讨论】:

    猜你喜欢
    • 2018-01-15
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多