在Laravel(PHP)控制器中使用JavaScript功能

发布于 2025-02-13 13:47:05 字数 1034 浏览 0 评论 0原文

我想在Laravel中间件中重新使用JavaScript代码,以从后端进行安全身份验证。

当前,JS代码使用Crypto-JS库,它的工作原理很好,因此我想简单地使用Laravel控制器中的JS功能。 我尝试使用本文中的JS代码: htttps:/ /www.geeksforgeeks.org/how-to-run-javascript-from-php/

但不是作品,它只是在前端回荡了纯文本。

这是我在PHP中尝试的:

<?php
namespace App\Http\Controllers;

class OAuthController extends Controller
{    
   public function testjsfunction() {
      return '<script type="text/javascript">  
         function myFunction(a, b) {
            return a * b;
         }
         // var x = myFunction(11, 10);
      </script>';
   }

   /**
    * my function called from web.php 
    * Route::get('/login', ([\App\Http\Controllers\OAuthController::class, 'getToken']));
    *
   */
   public function getToken($email, $password) 
   {
      $response = $this->testjsfunction();
      return $response;
   }
?>

这是可能的还是我应该使用PHP库重新创建所有内容?

I wanted to re-use my javascript code in a Laravel middleware to make a secure authentication from my back-end.

Currently, the js code uses the crypto-js library and it works perfectly fine, so I would like to simply use the JS functions from my Laravel controller.
I tried to use a js code like in this article : https://www.geeksforgeeks.org/how-to-run-javascript-from-php/

But it doesn't works, it just echoes the plain text in the front-end.

Here is what I tried in PHP:

<?php
namespace App\Http\Controllers;

class OAuthController extends Controller
{    
   public function testjsfunction() {
      return '<script type="text/javascript">  
         function myFunction(a, b) {
            return a * b;
         }
         // var x = myFunction(11, 10);
      </script>';
   }

   /**
    * my function called from web.php 
    * Route::get('/login', ([\App\Http\Controllers\OAuthController::class, 'getToken']));
    *
   */
   public function getToken($email, $password) 
   {
      $response = $this->testjsfunction();
      return $response;
   }
?>

Is it possible or should I just recreate everything with a PHP library ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

╰◇生如夏花灿烂 2025-02-20 13:47:05

您需要添加内容类型

尝试

    public function getToken($email, $password) 
    {
      return response($this->testjsfunction(), 200, [
                'Content-Type' => 'text/html'
            ]);
    }

You need to add content type

Try this

    public function getToken($email, $password) 
    {
      return response($this->testjsfunction(), 200, [
                'Content-Type' => 'text/html'
            ]);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文