我正在尝试为数据库中的用户更新字段,并且我正在尝试使用ajax执行此操作。 我有一个资源(风扇),在我的风扇控制器中,我有一个功能更新($id):
我像这样使用 ajax 调用:
var full_name = $("#user_name").val();
var full_location = $("#user_city").val();
request = $.ajax({
url: "http://url.com/fans/update",
type: "post", success:function(data){console.log(data);},
data: {'full_name': full_name, 'full_location': full_location} ,beforeSend: function(data){
console.log(data);
}
});
full_name和full_location正在被拉好。 不过,我不确定它们是否正确传递给函数。 console.logs 记录正常,但它们没有在控制台中显示正确的数据(它只是打印整个源)。
更新功能:
public function update($id)
{
//get saved info from fan profile
$full_name = Input::get('full_name');
$full_location = Input::get('full_location');
//echo var_dump($full_name);
$split_name = explode(" ", $full_name);
$first_name = $split_name[0];
$i=0;
foreach ($split_name as $name) {
if($i > 0) {
$last_name = $name[i] + " ";
}
$i++;
}
$trimmed_last_name = trim($last_name);
//find user
$fan = Fan::where('id', '=', $id)->first();
$fan->first_name = $first_name;
$fan->last_name = $trimmed_last_name;
$fan->save();
}
数据库没有更新,所以我假设没有调用该函数(即使 ajax 显示成功)。 我错过了什么? 谢谢。
转到终端/命令提示符,然后键入并运行以下命令:
php artisan routes
这将返回如下内容(有关应用程序中声明的所有路由的详细信息):
+--------+---------------------------------------------------------------+---------------+-------------------------------+----------------+---------------+
| Domain | URI | Name | Action | Before Filters | After Filters |
+--------+---------------------------------------------------------------+---------------+-------------------------------+----------------+---------------+
| | GET posts | posts.index | PostController@index | | |
| | GET posts/c | posts.create | PostController@create | | |
| | POST posts | posts.store | PostController@store | | |
| | GET posts/{posts} | posts.show | PostController@show | | |
| | GET posts/{posts}/edit | posts.edit | PostController@edit | | |
| | PUT posts/{posts} | posts.update | PostController@update | | |
| | PATCH posts/{posts} | | PostController@update | | |
| | DELETE posts/{posts} | posts.destroy | PostController@destroy | | |
+--------+---------------------------------------------------------------+---------------+-------------------------------+----------------+---------------+
从此结果中,找出用于该方法的适当url
。在这种情况下,对于使用请求method
PATCH
update
方法,您可以使用如下内容:
posts/10
由于它是资源控制器,因此可以使用如下所示的内容:
$.ajax({
url: "fans/10", // 10 is user id to update, for example
type: "post",
data: { full_name:full_name, full_location:full_location, _method:"PATCH" },
success:function(data){
console.log(data);
}
});
因此,您的update
方法将被匹配,因为您的update
方法如下所示:
public function update($id)
{
//...
}
根据您的url
,您应该声明以下路线(足智多谋):
Route::resource('fans', 'FansController');
如果您将JS
代码保存在 seoarate 文件中,那么您也可以查看这篇文章,它是关于如何将模型对象从服务器发送到客户端(作为 JavaScript
Object),这将有助于了解将id
从服务器发送到客户端的想法,因此您可以在JS
函数中使用id
。
您
没有将$id传递给控制器函数
$fan = Fan::where('id', $id)->first();
same as
$fan = Fan::find($id);
这些不会返回任何内容,因为未设置$id。
此外,您不会发回任何指定要更新的风扇的数据,例如 id。
更新:
如果您要通过帖子将 id 传回:
public function update() {
$id = Input::get('id');
$fan = Fan::find($id);
...
}