JavaScript 何时何地运行,PHP 怎么样?我可以将两者结合起来吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25093905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When and where does JavaScript run, how about PHP? Can I combine the two?
提问by Madara's Ghost
When does a client-side language like JavaScript run and when does a server-side language like PHP run? How can I mix both?
什么时候运行像 JavaScript 这样的客户端语言,什么时候运行像 PHP 这样的服务器端语言?我怎样才能混合两者?
I want to run a PHP function when a button on my site is clicked, or run a JavaScript function from PHP; is that possible?
我想在单击我网站上的按钮时运行 PHP 函数,或者从 PHP 运行 JavaScript 函数;那可能吗?
回答by Madara's Ghost
The short answer is No. You cannot run PHP functions from JavaScript[With the exception of AJAX], nor can you run JavaScript functions from PHP. The two run times are separate.
简短的回答是否定的。您不能从 JavaScript [AJAX 除外]运行 PHP 函数,也不能从 PHP 运行 JavaScript 函数。两个运行时间是分开的。
How?
如何?
To understand how JavaScript and PHP cooperate, you should first understand the basics of the HTTP protocol that powers the web.
要了解 JavaScript 和 PHP 如何协作,您应该首先了解支持 Web 的 HTTP 协议的基础知识。
The diagram above demonstrates the basics of the HTTP protocol. The user (you) asks the client (your browser) to fetch you a page. The browser will then ask the server (Google, in this example) for the page. The server will reply with an HTML page, the client parses that page, and asks for the images, fonts and any other resources needed to load the page correctly. The client then presents the completed page to the user.
上图展示了 HTTP 协议的基础知识。用户(您)要求客户端(您的浏览器)为您获取页面。然后浏览器将向服务器(在本例中为 Google)询问该页面。服务器将回复一个 HTML 页面,客户端解析该页面,并要求正确加载页面所需的图像、字体和任何其他资源。客户端然后将完成的页面呈现给用户。
So where does JavaScript come in?
那么 JavaScript 是从哪里来的呢?
JavaScript is run in the Client(i.e. the browser). So JavaScript runs after the response from the server has arrived. Let's add that to our diagram.
JavaScript在客户端(即浏览器)中运行。所以 JavaScript在来自服务器的响应到达后运行。让我们将其添加到我们的图表中。
JavaScript scripts start running as soon as they are loaded, and will continue to run if they have event listeners waiting for events from the user (like clicking, typing, or moving around).
JavaScript 脚本一加载就开始运行,如果它们有等待用户事件(如单击、键入或移动)的事件侦听器,它们将继续运行。
Where does PHP fit in?
PHP 适用于何处?
PHP runs on the Server, the web server (Which is a program responsible for serving web content) will run PHP according to its configuration. PHP will process the input from the web server, and return output. That output is served back to the client.
PHP运行在 Server 上,Web 服务器(负责提供 Web 内容的程序)将根据其配置运行 PHP。PHP 将处理来自 Web 服务器的输入,并返回输出。该输出返回给客户端。
Updated diagram:
更新图:
As you can see, the PHP execution does not persist. It is executed, and then ends once the response is sent.
如您所见,PHP 执行不会持续。它被执行,然后在发送响应后结束。
As you can see, there is no overlap between the PHP execution and the JavaScript execution, so it isn't actually possible to make a function on one of them to work based on input from the other.
如您所见,PHP 执行和 JavaScript 执行之间没有重叠,因此实际上不可能使其中一个的函数根据另一个的输入工作。
But.. but.. I've heard of AJAX!
但是……但是……我听说过 AJAX!
AJAX is merely causing another HTTP request from JavaScript. You can call it a way to use PHP functions from JavaScript, but it's actually not quite that.
AJAX 只是引起来自 JavaScript 的另一个 HTTP 请求。您可以将其称为从 JavaScript 使用 PHP 函数的一种方式,但实际上并非如此。
As you can see, with AJAX, JavaScript will send a request to the server, which will invoke PHP, PHP will run again, like in a normal request (PHP doesn't necessarily knows that this is even an AJAX request!) and the server returns the response back to JavaScript, which uses it to do stuff.
如您所见,使用 AJAX,JavaScript 将向服务器发送请求,服务器将调用 PHP,PHP 将再次运行,就像在正常请求中一样(PHP 不一定知道这甚至是 AJAX 请求!)并且服务器将响应返回给 JavaScript,JavaScript 使用它来做事。
In this case, there is an overlap between the time PHP runs and the time JavaScript runs, since JavaScript invoked a request.
在这种情况下,PHP 运行时间和 JavaScript 运行时间之间存在重叠,因为 JavaScript 调用了一个请求。
Also see:
另见:
回答by Zirak
Welcome to McBurger, a fancy (yeah right)burger joint. The smell of dried-up grease invades your nostrils, causing your bowels to gurgle with a mixture of disgust and delight. You patiently wait in line behind a mother of what should be human children. Finally, you meet the teenage cashier face to face, not without some pity. You order a burger (surprise) and some fries. You pay up and wait a bit for your order.
欢迎来到 McBurger,一家别致的(没错)汉堡店。干涸的油脂的气味侵入你的鼻孔,让你的肠子咕噜咕噜地混合着厌恶和喜悦。你耐心地在一个应该是人类孩子的母亲身后排队。最后,你面对面地见到了十几岁的收银员,不无遗憾。你点了一个汉堡(惊喜)和一些薯条。您付款并等待您的订单。
After some time, you get your burger, only to discover that they forgot your fries! You walk up to the cash register again, and ask for them. You again wait out for the fries to be ready. Once they are, you guzzle everything up and leave.
过了一段时间,你拿到了汉堡,却发现他们忘记了你的薯条!你再次走到收银台,并要求他们。你再次等待薯条准备好。一旦它们出现,你就狼吞虎咽地离开。
What does this have to do with anything?
这有什么关系?
The angsty cashier is the server, perhaps running php.
烦躁的收银员是服务器,可能正在运行 php。
You are the client, maybe a web browser capable of understanding html/css/js.
您是客户端,也许是能够理解 html/css/js 的网络浏览器。
To get service, you approach the counter and say "I want a burger". McBurger then prepares and gives you a burger.
要获得服务,您可以走到柜台说“我想要一个汉堡”。McBurger 然后准备并给你一个汉堡。
To get service, a web browser approaches the server and says "I want this page". Your server then prepares and gives you a page.
为了获得服务,网络浏览器接近服务器并说“我想要这个页面”。然后您的服务器准备并为您提供一个页面。
The most important aspect of this is that there is no mingling of customer and McBurger. You won't prepare your own fries, and McBurger won't drink your milkshake. The same way, the web browser will not run php, and the server will not run javascript for you. If you want McBurger to give you their famous caramel ice-cream, you must approach the counter and ask for one. If you want your web-page to save something to the DB when you click a button, you must approach the server and ask it to do so.
最重要的方面是没有客户和 McBurger 的混合。你不会自己准备薯条,McBurger 也不会喝你的奶昔。同样,网络浏览器不会运行 php,服务器也不会为您运行 javascript。如果你想让 McBurger 给你他们著名的焦糖冰淇淋,你必须靠近柜台并要一个。如果您希望您的网页在您单击按钮时将某些内容保存到数据库中,您必须接近服务器并要求它这样做。
You and McBurger communicate over sound. Browsers and servers communicate over HTTP.
您和 McBurger 通过声音进行交流。浏览器和服务器通过 HTTP 通信。
Let's take a look at HTTP.
让我们来看看 HTTP。
Rabbit, where have you taken me?
兔子,你带我去哪儿了?
If you're running on pretty much any linux distro or a Mac, you have netcat installed. If you're on Windows, sorry, you'll have to take my word for the next section, or download a nc port or a telnet client of some sort.
如果您几乎在任何 Linux 发行版或 Mac 上运行,那么您已经安装了 netcat。如果您使用的是 Windows,抱歉,您将不得不在下一节中相信我的话,或者下载 nc 端口或某种 telnet 客户端。
Anyway, open up your favourite terminal, and let's talk to some server on port 80 (the default http port):
不管怎样,打开你最喜欢的终端,让我们与端口 80(默认的 http 端口)上的某个服务器对话:
% nc www.stackoverflow.com 80
"Welp, that didn't do much of anything, there's just an empty prompt in front of me!"
“咳咳,那也没啥用,我面前只有一个空提示!”
Don't worry, random person whom I talk to during these answers, we just haven't said anything to the server! In McBurger, this'd be the equivalent of walking up to the counter and staring intently at the cashier.
别担心,我在这些回答过程中与随机人交谈,我们只是没有对服务器说任何话!在 McBurger,这相当于走到柜台前,专心地盯着收银员看。
Just.
只是。
Staring.
凝视。
We have to start using our vocal chords fast, or they'll call security. I can't go back to that hellhole Martha, I just...can't.
我们必须快速开始使用我们的声带,否则他们会打电话给保安。我不能回到那个地狱般的玛莎,我只是……不能。
...Anywho, we need to tell the cashier that we want a burger. In http, that's issuing a GET request:
...任何人,我们需要告诉收银员我们想要一个汉堡。在 http 中,这是发出 GET 请求:
% nc www.stackoverflow.com 80
GET / HTTP/1.1
Hit enter twice, and hurray, we got some output!
按 Enter 两次,欢呼吧,我们得到了一些输出!
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Date: Sat, 02 Aug 2014 10:55:16 GMT
Content-Length: 334
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
That can't be good. Lots of stuff I don't understand, but it says that the request hostname is invalid. Let's try that again, only we give it a host this time:
那不可能是好事。很多东西我不明白,但它说请求主机名无效。让我们再试一次,这次我们只给它一个主机:
% nc www.stackoverflow.com 80
GET / HTTP/1.1
Host: stackoverflow.com
Hit enter twice, and "holy bajesus, that's a lot of output!" Yes person, that is.
按两次回车,“天哪,输出太多了!” 是的人,就是这样。
Rabbit, how is this relevant?
兔子,这有什么关系?
So how is this connected to php and some flowcharts? Still think that you can run php on click? Let's write a "hello world" in php and see why it's not possible.
那么它是如何连接到 php 和一些流程图的呢?仍然认为您可以单击运行 php 吗?让我们在 php 中编写一个“hello world”,看看为什么它是不可能的。
Just for the occasion, I installed php and wrote some files:
只是为了这个场合,我安装了 php 并写了一些文件:
# example.php
<?php
echo 'Hi mom!';
?>
Cool, let's do a request and see what's happening:
很酷,让我们做一个请求,看看发生了什么:
% nc localhost 80
GET /example.php HTTP/1.1
Host: localhost
The ritual two enter keys and:
仪式二输入钥匙和:
HTTP/1.1 200 OK
Server: nginx/1.2.1
Date: Sat, 02 Aug 2014 11:00:52 GMT
Content-Type: text/html
Hi mom!
Congratulations, we have our own burger joint! We have a server, which we can respond to clients! Joy to the world!
恭喜,我们有了自己的汉堡店!我们有一个服务器,我们可以响应客户端!欢乐世界!
What happened here is this conversation:
这里发生的事情是这样的对话:
- Me: Give me
/example.php
. - Server: okay. Hey php, run
example.php
- php: Whatever. Output is
Hi mom!
- Server: There you go client,
Hi mom!
- Me: Thank you!
- 我:给我
/example.php
。 - 服务员:好的。嘿php,运行
example.php
- php:随便。输出是
Hi mom!
- 服务器:你去客户端,
Hi mom!
- 我:谢谢!
In conclusion
综上所述
- Server and client are two separate beings.
- They communicate over something called HTTP.
- If the client wants something, it has to ask the server for it.
- Which it does by doing HTTP requests.
- 服务器和客户端是两个独立的存在。
- 它们通过称为 HTTP 的东西进行通信。
- 如果客户端想要什么,它必须向服务器询问。
- 它通过执行 HTTP 请求来完成。
Shameless self-promotion: If you want to know how to create http requests from javascript, you can refer to my gist on the matter(warning: contains traces of swear words).
无耻的自我宣传:如果你想知道如何从javascript创建http请求,你可以参考我关于此事的要点(警告:包含脏话的痕迹)。
回答by K.K. Smith
The other answer is great, but I'll just try a simpler approach ..
另一个答案很好,但我会尝试一种更简单的方法..
Your browser receives a page of HTML and JavaScript from the server. PHP is working on the server to assemble that final page that gets sent to the browser. It can check some databases, and do some calculations, and maybe connect with an API, but at the end of it all it takes all the info and "prints it up" on a page full of code which it then sends to your browser.
您的浏览器从服务器接收 HTML 和 JavaScript 页面。PHP 正在服务器上工作以组装发送到浏览器的最终页面。它可以检查一些数据库,进行一些计算,并可能与 API 连接,但最后它会获取所有信息并在充满代码的页面上“打印”,然后将其发送到您的浏览器。
The browser gets the page and if there is any Javascript on the page, or if there are SCRIPT tags that pull in other .js files, it reads all that and then executes the Javascript.
浏览器获取页面,如果页面上有任何 Javascript,或者如果有其他 .js 文件的 SCRIPT 标签,它会读取所有这些,然后执行 Javascript。
So your page is "built" by PHP, and it can include Javascript into that somehow which will be executed by the browser, but these two processes are generally separate.
因此,您的页面是由 PHP “构建”的,它可以将 Javascript 包含到浏览器执行的某种方式中,但这两个过程通常是分开的。
You can get PHP to "talk" to Javascript by outputting specific JS code onto the page.
您可以通过将特定的 JS 代码输出到页面上,让 PHP 与 Javascript 进行“对话”。
You can get Javascript to "talk" to PHP by using AJAX to contact the server while a page is executing. The server can give answer info back which is then integrated back into the page using Javascript again.
通过在页面执行时使用 AJAX 联系服务器,您可以让 Javascript 与 PHP 进行“对话”。服务器可以返回答案信息,然后再次使用 Javascript 将其集成回页面。
But generally, the two processes are running in their own worlds.
但一般来说,这两个进程都在各自的世界中运行。
You can do you "button starts PHP code" best with AJAX.
你可以用 AJAX 最好地“按钮启动 PHP 代码”。
Running Javascript from "inside" PHP is not really done.
从“内部” PHP 运行 Javascript 并没有真正完成。