Javascript 将数据插入数据库。Cakephp、AJAX、jQuery、异步

Javascript 将数据插入数据库。Cakephp、AJAX、jQuery、异步,javascript,ajax,database,cakephp,Javascript,Ajax,Database,Cakephp,我有一个非常简单的任务要做。我在我的前端分配了一个值,我想将其异步发送到后端 “我的视图”中的以下html代码: <p id="p">Test</p> <form id='formId' onclick="save()" method="post"> <input class="save" type="submit" value="save" > </input> </form> 我希望s

我有一个非常简单的任务要做。我在我的前端分配了一个值,我想将其异步发送到后端

“我的视图”中的以下html代码:

<p id="p">Test</p>
    <form id='formId' onclick="save()"  method="post">
        <input class="save" type="submit" value="save" > </input>
    </form>

我希望
savedVal
的值以异步方式发送到我的控制器,并从那里保存到我的数据库中。

我假设您知道如何通过ajax发送post数据。我的回答将集中在您问题的CakePHP控制器操作部分

在控制器中

public function saveJSON()
{
    $jsonResponseArray = [] //Your response array
    if($this->request->is('post'))
    {
      $myModelEntity = $this->MyModel->newEntity($this->request->data);
      $mySavedData = $this->MyModel->save($myModelEntity);
      if($mySavedData)
      {
        $jsonResponseArray = ; //Whatever data you want to send as a response
      }
      else
      {
         //Save failed
          $jsonResponseArray = ; //Whatever data you want to send as a response
       }

     }
        $json = json_encode($jsonResponseArray);
        $this->autoRender = false;
        $this->response->type ( 'json' );
        $this->response->body ( $json );
}
仅供参考,此答案使用CakePHP 3.0

  ///A bit of JQuery to get you started
        $.ajax({
        type: 'post',
        url: "http://" + window.location.hostname
                + "/Controller/saveJSON",
        data: {
            p: $('#p').val()
        },
        success: function(result) {
           //JSON seponse comes the the variable named result
        },
        dataType: 'json',
        global: false
    });
不是onclick=“save()”而是onsubmit=“save()”。元素不需要结束元素。你可以用。
  ///A bit of JQuery to get you started
        $.ajax({
        type: 'post',
        url: "http://" + window.location.hostname
                + "/Controller/saveJSON",
        data: {
            p: $('#p').val()
        },
        success: function(result) {
           //JSON seponse comes the the variable named result
        },
        dataType: 'json',
        global: false
    });