du521521521 2014-01-02 18:26
浏览 32
已采纳

从JQuery发送请求到CakePHP

I am creating a web application that uses CakePHP as the back end and JQuery as the front end. In order to communicate with the server, I wanted to make GET and Post requests from JQuery using ajax. Here is what I have right now:

function submit_registration(fname, lname, email, pass)
{
  var arr = { data: {User: { fname: fname, lname: lname, email: email, password: pass }}};

  $.post('http://localhost/cake2/users/add', JSON.stringify(arr), function(response){
  alert(response);
  })
}

That is in JQuery. Here is the add action in CakePHP:

public function add()
{   
    $this->layout = null ;

    if ($this->request->is('post'))
    {
        $data = $this->request->input('json_decode');
        $this->User->create();

        if ($this->User->save($data))
        {
            $this->set('data', "success");
            $this->render('/General/JsonMode2/');
        }
        else
        {
            $this->set('data', "failure to save");
            $this->render('/General/JsonMode2/');
        }
    }
    else
    {
        $this->set('data', "failure to post");
        $this->render('/General/JsonMode2/');
    }
}

It renders as JSON back to the front end. My problem is, nothing happens when I submit the request. I put alerts to ensure that the submit_registration function was being called. Can anyone give me a clue as the what is going on?

  • 写回答

1条回答 默认 最新

  • dongliyan9190 2014-01-03 09:54
    关注

    change the script function to this:

    function submit_registration(fname, lname, email, pass)
    {
      var data = {User: { fname: fname, lname: lname, email: email, password: pass }};
    
      $.post('http://localhost/cake2/users/add', data, function(response){
      alert(response);
      })
    }
    

    and change $data = $this->request->input('json_decode'); to

    $data = $this->data;
    

    To debug the response, use CakeResponse like this:

    return new CakeResponse(array('body'=> json_encode('...message here...'),'status'=>200));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?