我有一个带有动态组件的 AJAX 特色页面。我想知道如何在 MVC 中处理 ajax 调用。
我的第一个想法是为 ajax 调用创建一个新的 Controller ,而不渲染 View ,并检查像这样的 ajax 请求的路由
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
call_user_func_array(array("ajax", $this->url_action), null);
}
最佳答案
我会让 AJAX 处理代码的位置取决于其上下文。如果它处理与返回完整 View 的另一个 Controller 相同类型的内容,只需在该 Controller 中创建一个“ajax 方法”,该方法用 JSON header 、您想要发送到浏览器的内容进行响应并退出。实际上并不需要专用的 AJAX Controller ,就像您没有单独的 GET Controller 或 POST Controller 一样。
编辑:(示例)
class BookController
{
public function getBookDetail($id)
{
// Go fetch a book from the DB.
// Assemble your full fledged view
// Send it to the browser
}
public function ajaxBookDetail($id)
{
// Go fetch a book from the DB.
header('Content-Type: application/json');
echo json_encode($someBookData);
exit;
}
}
如果您在以下位置检测到 xmlhttprequest
,则可以告诉路由器使用 ajax
前缀的方法而不是 get
前缀的方法SERVER header 。
关于php - MVC 结构 PHP 中的 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296122/