【发布时间】:2013-12-11 19:16:42
【问题描述】:
我想问你如何发送 ajax 请求并通过 jQuery 表单序列化并从控制器接收 JSON 响应?我一直在尝试很多解决方案,但没有一个对我有用。我在这方面有一点经验。
你能举个很好的例子吗?谢谢!
- 通过 AJAX 以序列化形式 (POST) 发送帖子
- 在控制器函数中处理动作并在 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