[英]How to call a PHP page from a javascript page using express functions
I'm trying to display a php page using javascript with express functions. 我正在尝试使用具有快速功能的javascript显示php页面。 An example code:
示例代码:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
I have a php page with html and javascript functions that displays different data from database and I'm not sure how to call the page from the javascript file. 我有一个带有html和javascript函数的php页面,该页面显示来自数据库的不同数据,并且我不确定如何从javascript文件调用该页面。 I tried putting it in script tags on the php page but how do I then execute the output of the php page in the res.send();
我尝试将其放在php页面的脚本标签中,但是如何在res.send()中执行php页面的输出;
You're getting things wrong. 你弄错了。 You can't load your express code into your PHP or vice versa (in fact you can, but it would be too much work).
您不能将您的快速代码加载到PHP中,反之亦然(事实上,您可以加载 ,但是这样做会太多)。
To make your PHP code talk to your express/node code, you should create an interface between them. 为了使您的PHP代码与您的express / node代码对话 ,您应该在它们之间创建一个接口。 I think a RESTful interface would be the easiest one to build.
我认为RESTful接口将是最容易构建的接口。 The code you've provided is already a RESTful interface.
您提供的代码已经是RESTful接口。
Then, in your PHP code (alongside with HTML and client-side JavaScript), you can 然后,在您的PHP代码中(连同HTML和客户端JavaScript),您可以
res.json({hello: 'Hello World'})
. More about Express json response here ). res.json({hello: 'Hello World'})
。 JSON响应这里 )。 EDIT: Ok, here is some PHP code: 编辑:好的,这是一些PHP代码:
<?php
$url = "localhost:3000/"; // this should the route you've defined on
// express. the `app.get('/')` part.
$json = file_get_contents($url);
var_dump(json_decode($json));
?>
And your express code should be like: 您的快递代码应类似于:
app.get('/', function(req, res){
res.json({hello: 'Hello World'})
})
Then, your PHP's var_dump
should output: 然后,您的PHP的
var_dump
应该输出:
{hello: 'Hello World'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.