简体   繁体   中英

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. 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. 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();

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).

To make your PHP code talk to your express/node code, you should create an interface between them. I think a RESTful interface would be the easiest one to build. The code you've provided is already a RESTful interface.

Then, in your PHP code (alongside with HTML and client-side JavaScript), you can

  • make an XHR or Ajax request to the express/node route (but you'll need to send a json, which is not so different from what you got: res.json({hello: 'Hello World'}) . More about Express json response here ).
  • Or, you do use a JSON request from PHP, which you can find more information here .

EDIT: Ok, here is some PHP code:

<?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:

{hello: 'Hello World'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM