2014-11-23 33 views
0

我有一個非常簡單的任務。我在我的前端分配了一個值,我希望將其異步發送到我的後端。將數據插入數據庫。 CakePHP,AJAX,JQery,異步

我認爲裏面的html代碼如下:

  <p id="p">Test</p> 

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

我得到我要發送的異步用下面的jQuery代碼

function save() { 
     var savedVal = $("#p").text(); 
     if (savedVal.length > 0) { 
      $("#p").text("saving..."); 
      $("#p").text(""); 
      return savedVal 
     } 
     else 
      alert("There is nothing to send!"); 
    } 

內容我想的savedVal的值被髮送到我的控制器異步,並從那裏將其保存在我的數據庫。

+0

代替的onclick = 「保存()」 是應該的onsubmit = 「保存()」。 元素不需要關閉元素。您可以使用。 – jeff 2014-11-23 11:47:37

回答

1

我會假設你有一個關於如何通過ajax發送發佈數據的想法。我的回答將集中在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); 
} 

FYI這個答案是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 
    });