Sha*_*adi 0 php ajax jquery slim
我正在使用简洁的框架与雄辩与数据库交谈.我正在尝试制作一个简单的发布ajax请求,将数据发布到db.所以我有这条路线:
//post yell
$app->post('/yell', 'UserController:postYell')->setName('yell');
Run Code Online (Sandbox Code Playgroud)
这个控制器解决了这个问题
public function postYell($request, $response)
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user'],
]);
return $response->withRedirect($_SERVER['HTTP_REFERER']);
}
Run Code Online (Sandbox Code Playgroud)
我试过这样的事情:
$(".postYell").submit(function(){
$.ajax(
{
url: "/yell",
type: 'POST',
data: {
"_method": 'POST',
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
Run Code Online (Sandbox Code Playgroud)
但我认为这不是正确的做法.如果我错过了一些显而易见的东西,我仍然很陌生.我找不到一个很好的例子,说明如何使用纤薄的东西,我已经被困在如何做几个小时了,所以如果有人能指出我正确的方向,我会非常感激
// Make sure you specify a valid callable with two ':'
$app->post('/yell', 'UserController::postYell')->setName('yell');
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器中,当它通过XHR时不要重定向:
public function postYell(Request $request, Response $response) : Response
{
$yell = Yell::create([
'body' => $request->getParam('yellBody'),
'user_id' => $_SESSION['user']
]);
if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
return $response;
} else {
return $response->withRedirect($request->getHeader('Referer'));
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的AJAX请求发送正确的数据值的配置跟进(jQuery.ajax会自动添加X-Requested-With: XMLHttpRequest如记录在这里下的"标题")
$('form.postYell').submit(function (e) {
// prevent the page from submitting like normal
e.preventDefault();
$.ajax({
url: '/yell',
type: 'POST',
data: $(this).serialize(),
success: function () {
console.log('it worked!');
},
error: function () {
console.log('it failed!');
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3669 次 |
| 最近记录: |