gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:21:30 25 4
gpt4 key购买 nike

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

我的 View 中包含以下 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 的值异步发送到我的 Controller ,并从那里将其保存在我的数据库中。

最佳答案

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

在你的 Controller 中

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
});

关于javascript - 将数据插入数据库。 Cakephp、AJAX、jQuery、异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com