hyperf写一个页面
时间: 2023-10-21 19:03:37 浏览: 39
Hyperf 是一个后端框架,不适合直接用于编写页面。但是可以通过 Hyperf 编写 API 接口,然后在前端页面中调用这些接口,从而渲染页面。以下是一个简单的示例:
首先,在 Hyperf 中编写一个返回数据的接口:
```php
<?php
declare(strict_types=1);
namespace App\Controller;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
/**
* @Controller()
*/
class HelloController
{
/**
* @GetMapping(path="/hello")
*/
public function index()
{
return [
'message' => 'Hello, world!',
];
}
}
```
然后,在前端页面中使用 JavaScript 代码调用该接口,并将返回的数据渲染到页面中:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<div id="message"></div>
<script>
fetch('/hello')
.then(response => response.json())
.then(data => {
document.getElementById('message').innerHTML = data.message;
});
</script>
</body>
</html>
```
在上面的代码中,我们使用了 fetch 函数来发起 HTTP 请求,然后使用 Promise 来处理返回的数据,并将结果渲染到页面中。当然,这只是一个简单的示例,实际情况下可能需要更加复杂的逻辑来处理数据和渲染页面。