-1

I have a table (SQL Server 2008) that have field1 and field2. if the check box myCheckBox is checked, then the value for <label id="priceLabel" /> will use the value in field1 and if it's not checked, the label will use the value from field2.

I don't understand AJAX very well so I'm thinking that I should use javascript in changing the label's value without having to reset all the other components' values. I read that we shouldn't use javascript to connect to database but I don't know of any other way..

can someone tell me what to do in this situation?

4

2 回答 2

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 方面,您将在内存结构(数组等)中构建数据,然后将其转换为字符串以与echovia 一起使用json_encode。在 JavaScript 方面,您将JSON.parse在现代浏览器上解析该 JSON。(对于较旧的浏览器,您必须在页面中添加 JSON 解析器,这是使用像 jQuery 这样的优秀库的另一个原因,它为您提供了一个。)

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

<!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>

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

于 2013-08-01T08:11:33.090 回答
0

如果您不需要太疯狂的东西......
您可以简单地预加载 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>

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

于 2013-08-01T08:57:38.523 回答