【问题标题】:I have to combine php and javascript我必须结合 php 和 javascript
【发布时间】:2013-08-01 08:03:56
【问题描述】:

我有一个包含 field1 和 field2 的表 (SQL Server 2008)。如果选中复选框myCheckBox,则<label id="priceLabel" /> 的值将使用field1 中的值,如果未选中,标签将使用field2 中的值。

我不太了解 AJAX,所以我想我应该使用 javascript 来更改标签的值,而不必重置所有其他组件的值。我读到我们不应该使用 javascript 连接到数据库,但我不知道任何其他方式..

谁能告诉我在这种情况下该怎么办?

【问题讨论】:

  • 标题应该是“结合”..
  • 使用 Ajax 意味着使用 JS 或 jQuery。 “有人能告诉我在这种情况下该怎么办吗?”不清楚。
  • 而使用jQuery隐式意味着使用JS。
  • @GolezTrol 非常真实!
  • 但是你当时应该解决一个问题。您主要关心的似乎是了解 Ajax。您不需要为此使用数据库,因此请不要使用 SQL Server。

标签: php javascript sql database


【解决方案1】:

这是一个大致的工作原理图:

用户工作站 |您的服务器
                       |
+--------------+ | +-------------+ +-------------+
|浏览器 | | | PHP | | |
+--------------+ | +--------------+ |数据库 |
| JavaScript || PHP 代码 || |
|代码 |阿贾克斯 | |与 DB 对话 | | |
+--------------+ | +-------------+ +-------------+

因此,您的 JavaScript 代码使用 ajax 与您的 PHP 代码对话。您的 PHP 代码与您的数据库对话。即使您设置了基础设施,浏览器上的 JavaScript 也不应该用于直接与您的数据库对话,因为它当然是在最终用户的浏览器上运行的,因此它必须具有有限的权限。您必须保护您的数据库免受外界影响。

这就是您的 PHP 代码的作用:它既是看门人又是数据转换器。它从数据库中获取数据,将其转换为对客户端有用的格式(通常是 HTML、文本、JSON 或 XML),然后将其传递给浏览器中的 JavaScript 代码,然后浏览器使用该 HTML,文本、JSON 或 XML 向用户显示某些内容或类似内容。

看看那些(稍微)更详细的:

  1. JavaScript Ajax 请求

    使用 JavaScript 发送 ajax 请求非常容易,特别是如果您使用一个不错的库来解决一些浏览器的不一致问题。基本上,它看起来像这样:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleReadyStateChange;
    xhr.open("GET", "your_php_file.php");
    xhr.send();
    function handleReadyStateChange() {
        if (xhr.readyState === 4 && (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300))) {
            // ===> This is where we can use the resulting information <===
        }
    }
    

    让我们更详细地看一下:

    // Create the request object
    var xhr = new XMLHttpRequest();
    
    // Set up a callback for when things happen
    xhr.onreadystatechange = handleReadyStateChange;
    
    // Open the request
    xhr.open("GET", "your_php_file.php");
    //       ^      ^----------------------- a normal URL like any other
    //       |------------------------------ the kind of request (GET, POST, ...)
    
    // Send it (if this were a POST, you'd include data as an
    // argument to `sent`, typically as a URI-encoded string
    xhr.send();
    
    // IMPORTANT: As of this point in the code, the request has been
    // *sent*, but it has not yet *completed*. By default, ajax is
    // *asynchronous*.
    
    // Our callback for ready state changes
    function handleReadyStateChange() {
        // Is the request complete?
        if (xhr.readyState === 4) { // 4 = complete
            // Yes, did it succeed? (`status` is a standard HTTP status code
            // except that *some* browsers sometimes use 0 if the response came
            // from cache)
            if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
                // If the Content-Type header of the HTTP response was for XML,
                // the XML document is on `xhr.responseXML`.
                // Otherwise, the HTML, text, or JSON is on `xhr.responseText`
    
                // ===> This is where we can use the resulting information <===
            }
        }
    }
    
  2. PHP 代码

    ajax 请求看起来像对 PHP 代码的任何其他页面请求。 (如果需要,可以将它们区分开来,但很少需要这样做)。因此,您的 PHP 代码就像您编写的任何其他 PHP 代码一样。不过,它可能会有不同的输出。您习惯于 PHP“页面”为浏览器呈现完整的 HTML 页面。但是,在响应 ajax 请求时,您不会发回整个页面,而是发回页面上的代码将使用的信息。

    这是 PHP 的一个示例,但同样,由于这与您编写的其他 PHP 一样,它可以是任何东西

    <?php
        // In our case, we'll return plain text from our example, so
        // mark the response accordingly
        header("Content-Type", "text/plain");
    
        // We might use $_GET or $_POST variables here, to get
        // information from the request
    
        // Once we've authenticated that the request comes from
        // an authorised user, we might connect to the database
        // and retrieve some information here
    
        // Output our response
        echo("Hi there");
    ?>
    

    我们正在返回纯文本。同样,您可以退回很多东西。当您将数据返回到页面时,JSON 很受欢迎。在 PHP 方面,您将在内存结构(数组等)中构建数据,然后通过json_encode 将其转换为与echo 一起使用的字符串。在 JavaScript 方面,您将在现代浏览器上使用 JSON.parse 解析该 JSON。 (对于较旧的浏览器,您必须在页面中添加 JSON 解析器,这是使用像 jQuery 这样的优秀库的另一个原因,它为您提供了一个。)

下面是 HTML 和 JavaScript 端的完整示例:Live Copy | Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Ajax Example</title>
  <style>
    #theSpan {
      border: 1px solid grey;
      padding: 2px;
    }
  </style>
</head>
<body>
  <input type="button" id="theButton" value="Click Me">
  <p>Here is the span we'll fill in: <span id="theSpan"></span></p>
  <script>
    (function() {
        // Hook up our button click handler
        document.getElementById("theButton").onclick = function() {
            // Do our ajax request

            // Create the request object
            var xhr = new XMLHttpRequest();

            // Set up a callback for when things happen
            xhr.onreadystatechange = handleReadyStateChange;

            // Open the request
            xhr.open("GET", "/uvanep/1");
            //       ^      ^----------------------- a normal URL like any other
            //       |------------------------------ the kind of request (GET, POST, ...)

            // Send it (if this were a POST, you'd include data as an
            // argument to `sent`, typically as a URI-encoded string
            xhr.send();

            // IMPORTANT: As of this point in the code, the request has been
            // *sent*, but it has not yet *completed*. By default, ajax is
            // *asynchronous*.

            // Our callback for ready state changes
            function handleReadyStateChange() {
                // Is the request complete?
                if (xhr.readyState === 4) { // 4 = complete
                    // Yes, did it succeed? (`status` is a standard HTTP status code
                    // except that *some* browsers sometimes use 0 if the response came
                    // from cache)
                    if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
                        // If the Content-Type header of the HTTP response was for XML,
                        // the XML document is on `xhr.responseXML`.
                        // Otherwise, the HTML, text, or JSON is on `xhr.responseText`

                        // ===> This is where we can use the resulting information <===
                        // In this case, let's put it in our span:
                        document.getElementById("theSpan").appendChild(
                          document.createTextNode(xhr.responseText)
                        );
                    }
                }
            }
        };
    })();
  </script>
</body>
</html>

在这种情况下,我们调用的页面只返回文本"Hi there"

【讨论】:

  • 漂亮的图表。补充一下,Ajax 请求(几乎)与关于 PHP 的普通请求相同。唯一的区别是它由 Javascript 触发并由 Javascript 处理,而不是在浏览器中显示新页面。 (当然还有这个额外的标头,以防 PHP 想知道它是否是 Ajax。)
【解决方案2】:

如果你不需要太疯狂的东西......
您可以简单地预加载 2 个字段,使视图中的值可访问,并使用 JavaScript 切换值:

<?php
  $label1 = 'field1_value'; //get this value from the DB
  $label2 = 'field2_value'; 
?>

<html>
    <input type="checkbox" id="myCheckBox" onclick="changeValue();" />
    <label id="priceLabel" ><?php echo $label1; ?><label>

     <script type="text/javascript">
        function changeValue(){
           var check = document.getElementById('myCheckBox');
           var label = document.getElementById('priceLabel');

           if(check.checked){
               label.innerHTML = "<?php echo $label2; ?>";
           }else{
               label.innerHTML = "<?php echo $label2; ?>";
           }
        }
    </script>

<html>

它可能会做得更好,只是在这里展示这个概念。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2018-04-06
    • 1970-01-01
    • 2018-03-27
    • 2015-04-16
    • 2019-02-12
    • 2021-02-04
    相关资源
    最近更新 更多