我有一项非常简单的任务。我在前端分配了一个值,我希望将其作为异步发送到我的后端。
我视图中的以下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 :(得分: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 );
}
仅供参考,这个答案在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
});