编程

使用 PHP2JS 在 PHP 和 JavaScript 之间分享数据

298 2024-01-05 23:31:00

Laravel 的 PHP2JS 包是标准化 PHP 和 JavaScript 之间共享数据过程的一种方法。有很多方法可以在前端和后端之间共享数据,所以这个包可能不适合所有人,但它可以提供一个简单的解决方案,以一致的方式与 JavaScript 共享数据。

以下是文档中的一个示例,该示例说明了此包如何将来自控制器的数据分享给视图,使得 JavaScript 可访问:

使用 JavaScript 可访问的视图共享来自控制器的数据:

class YourController extends Controller
{
    public function index()
    {
        return view('welcome')->with([
            'moonLandingDate' => '1969-07-20'
        ])->toJS();
    }
}

 这是通过 PHP2JS 对象提供的,该对象包含视图中的数据:

let moonLandingDate = PHP2JS.data.moonLandingDate;
// '1969-07-20'

您也可以使用 toStrictJS()方法定义应与视图共享的值,这些值与传递给 Blade 视图的值分开:

$astronauts = [
    'Neil Armstrong',
    'Buzz Aldrin',
    'Michael Collins'
];
 
return view('welcome')->with([
    'astronauts' => $astronauts
])->toStrictJS([
    'spacecraft' => "Lunar Module Eagle",
    'event'      => "Apollo 11 Moon Landing",
]);

最后,你也可以通过包函数上的 PHP2JS 对象使用 JavaScript 可用的数据对象:

// Assign a copy of the object to a new variable at runtime.
// Remember to replace PHP2JS with the Alias you have used.
const __PHP = PHP2JS.assign();
 
// Extract data or validate if it exists in
// the object delivered by PHP:
const post = PHP2JS.only('post');
const hasPost = PHP2JS.has('post');
 
// Get a value
PHP2JS.get("date");

该软件包还提供了一个名为 QuickRequest 的工具,以简化从 JavaScript 向 Laravel 后端发出 API 请求:

/**
 * Considering that this value is retrieved from
 * somewhere in a JS variable.
 */
const idRecord = 10;
 
/**
 * Use the route structure created in web.php.
 */
QuickRequest().get({
    url: '/record/' + idRecord,
    success: function (res) {
        console.log("Successful Process, Data: ", res.data);
    },
    error: function (err) {
        console.error("Error: " + err.data.message);
    }
});

您可以了解有关此软件包的更多信息,获取完整的安装说明,并在官方文档中查看示例;项目源代码也可以在 GitHub 上 rmunate/PHP2JS 上获得。