gpt4 book ai didi

javascript - Ajax表单数据未保存在数据库中

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

我正在尝试在 Laravel-5.2 中使用 Ajax 将用户输入保存到数据库中。

这是我的route.php

Route::get('xxxxx/{task_id?}',function($task_id){
$task = App\XXXXX::find($task_id);

return response()->json($task);
});

Route::put('xxxxx/{task_id?}',function(Request $request,$task_id){
$task = App\XXXXX::find($task_id);

$task->Name = $request->Name;//
$task->Email = $request->Email;
$task->Telephone = $request->Telephone;

$task->save();

return response()->json($task);
});

在我看来,保存按钮的用途是。

<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" value="update">Save changes</button>
<input type="hidden" id="task_id" name="task_id" value="0">
</div>

我的js文件使用this tutorial.创建。
我收到弹出窗口,保存按钮不起作用。
这里出了什么问题?我是 Ajax 新手。
提前致谢。

最佳答案

这是route.php

路线::match(['get','post'],'my/save-data','MyController@SaveData');

这是您的 html:

保存更改

这是您的 Controller 文件:MyController.php

公共(public)函数SaveData(请求$request) { $input = $request->all();

    try{

// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();

// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();

$otherModel = $input['Name'];
$otherModel = $input['Email'];
$otherModel = $input['Telephone'];

// save
$otherModel->save();

}
catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
\Log::error( $e->getMessage(), $context );
}
catch (Exception $e){
\Log::error( $e->getMessage(), $context);
}

return response()->json( ['status'=>'success', 'message'=>'Completed successfully'] );
}
<小时/>

这是你的Js文件:save.js

函数保存() { 获取数据 = { name: "value",//来自 get eliment
email: "value",//来自 get eliment 电话:“值”//来自获取元素 };

$.ajax({
type: 'post', // POST Request
url: 'localhost/my/save-data', // localhost/my/save-data // Url of the Route (in this case user/save not only save)
data: getData, // Serialized Data

beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');

if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler

// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});

}

关于javascript - Ajax表单数据未保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39570145/

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