温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - What is the difference between client-side and server-side programming?
client-side javascript php server-side

javascript - 客户端编程和服务器端编程有什么区别?

发布于 2020-03-27 10:38:10

我有以下代码:

<script type="text/javascript">
    var foo = 'bar';
    <?php
        file_put_contents('foo.txt', ' + foo + ');
    ?>

    var baz = <?php echo 42; ?>;
    alert(baz);
</script>

为什么这不将“ bar”写入我的文本文件,而是发出“ 42”警报?


注意:此问题的早期修订版本明确涉及服务器上的PHP和客户端上的JavaScript。当一种语言在客户端上运行而另一种语言在服务器上运行时,问题和解决方案的本质对于任何一对语言都是相同的(即使它们是相同的语言)。当您看到有关特定语言的答案时,请考虑到这一点。

查看更多

查看更多

提问者
被浏览
187
2017-05-23 20:02

Your code is split into two entirely separate parts, the server side and the client side.

                    |
               ---------->
              HTTP request
                    |
+--------------+    |    +--------------+
|              |    |    |              |
|    browser   |    |    |  web  server |
| (JavaScript) |    |    |  (PHP etc.)  |
|              |    |    |              |
+--------------+    |    +--------------+
                    |
  client side       |      server side
                    |
               <----------
          HTML, CSS, JavaScript
                    |

The two sides communicate via HTTP requests and responses. PHP is executed on the server and outputs some HTML and maybe JavaScript code which is sent as response to the client where the HTML is interpreted and the JavaScript is executed. Once PHP has finished outputting the response, the script ends and nothing will happen on the server until a new HTTP request comes in.

The example code executes like this:

<script type="text/javascript">
    var foo = 'bar';
    <?php
        file_put_contents('foo.txt', ' + foo + ');
    ?>

    var baz = <?php echo 42; ?>;
    alert(baz);
</script>

Step 1, PHP executes all code between <?php ?> tags. The result is this:

<script type="text/javascript">
    var foo = 'bar';

    var baz = 42;
    alert(baz);
</script>

file_put_contents呼叫并没有导致任何东西,它只是写了“+富+”到文件中。<?php echo 42; ?>调用导致输出“ 42”,该输出现在位于该代码以前所在的位置。

现在,此生成的HTML / JavaScript代码将发送到客户端,并在客户端进行评估。alert调用有效,而该foo变量未在任何地方使用。

在客户端甚至开始执行任何JavaScript之前,所有PHP代码都在服务器上执行。JavaScript可以与之交互的响应中没有剩下PHP代码。

要调用一些PHP代码,客户端将必须向服务器发送新的HTTP请求。使用三种可能的方法之一可以发生这种情况:

  1. 链接,使浏览器加载新页面。
  2. 表单提交,它将数据提交到服务器并加载新页面。
  3. 一个AJAX请求,这是一个JavaScript技术,使一个普通的HTTP请求到服务器(如1和2会),而无需离开当前页面。

这是一个更详细地概述这些方法的问题

您还可以使用JavaScript来window.location模拟或可能性1.和2. ,使浏览器使用或提交表单来打开新页面