2013-08-01 1 views
-1

field1과 field2가있는 테이블 (SQL Server 2008)이 있습니다. myCheckBox 확인란을 선택하면 <label id="priceLabel" />의 값은 field1의 값을 사용하고 선택되어 있지 않으면 레이블은 field2의 값을 사용합니다.php와 javascript를 결합해야합니다.

저는 AJAX를 잘 이해하지 못하기 때문에 다른 모든 구성 요소의 값을 재설정하지 않고도 레이블 값을 변경하는 데 javascript를 사용해야한다고 생각합니다. 나는 우리가 데이터베이스에 연결하기 위해 자바 스크립트를 사용해서는 안되지만 다른 방법을 모른다는 것을 읽었습니다.

누군가이 상황에서 무엇을해야하는지 말해 줄 수 있습니까?

+1

제목이 "결합"되어 있어야합니다 .. – dapidmini

+0

Ajax를 사용한다는 것은 JS 또는 jQuery를 사용한다는 의미입니다. "누군가이 상황에서해야 할 일을 말해 줄 수 있니?" 분명하지 않다. – alfasin

+0

그리고 jQuery를 사용하면 암시 적으로 JS 사용을 의미합니다. – GolezTrol

답변

1

여기이 작동하는 방법의 대략적인 그림이다 :

User's Workstation  |    Your Server(s) 
         | 
+-------------+  | +-------------+  +-------------+ 
| Browser |  | |  PHP  |  |    | 
+-------------+  | +-------------+  |  DB  | 
| JavaScript |<---------->| PHP Code |<--->|    | 
| code  | ajax | | talks to DB |  |    | 
+-------------+  | +-------------+  +-------------+

그래서 자바 스크립트 코드는 PHP 코드로 얘기 아약스를 사용합니다. PHP 코드가 DB와 대화한다. 인프라 스트럭처를 설정하더라도 브라우저의 JavaScript는 DB와 직접 대화하는 데 사용해서는 안됩니다. 물론 최종 사용자의 브라우저에서 실행되므로 제한된 권한을 가져야합니다. DB를 외부 세계로부터 보호해야합니다.

PHP 코드는 게이트 키퍼와 데이터 변환기 모두입니다. DB에서 데이터를 가져와 클라이언트 (일반적으로 HTML, 텍스트, JSON 또는 XML)에서 유용하게 사용할 수있는 형식으로 변환 한 다음이를 브라우저의 JavaScript 코드로 전달한 다음 해당 HTML을 사용합니다. 텍스트, JSON 또는 XML을 사용하여 사용자에게 또는 유사한 것을 보여줄 수 있습니다. (약간) 더 자세히 사람들을 보면

: 아약스 요청을 보내 자바 스크립트를 사용하여

  1. 자바 스크립트 Ajax 요청

    당신이 해결할 수있는 괜찮은 라이브러리를 사용하는 경우 특히 매우 쉽습니다 일부 브라우저 불일치. 기본적으로는 다음과 같습니다

    // 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 코드 아약스 요청이 PHP 코드를 다른 페이지 요청과 같은

    :

    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 <=== 
        } 
    } 
    

    이 더 자세히 그 살펴 보자 . (필요한 경우 따로 구분할 수는 있지만 필요한 경우는 드뭅니다.) 따라서 PHP 코드는 작성한 다른 PHP 코드와 같습니다. 그것은 아마 다른 출력을 가지고있을 것이다. PHP "페이지"를 사용하여 브라우저의 완전한 HTML 페이지를 렌더링합니다. 하지만 Ajax 요청에 응답 할 때 전체 페이지를 다시 보내지 않으면 페이지에서 사용할 코드가 다시 전송됩니다. 이

    <?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"); 
    ?> 
    

    우리가 일반 텍스트를 반환하고이 단지 당신이 쓰는 다른 PHP처럼 그대로

    여기 다시 PHP의 모양에 대한 하나의 예이지만, 그것은 아무것도 될 수 있습니다 . 다시 말하지만, 당신은 많은 것을 돌려 줄 수 있습니다. JSON은 데이터를 페이지로 반환 할 때 널리 사용됩니다. PHP 쪽에서는 메모리 구조 (배열 등)에 데이터를 구축 한 다음 echojson_encode을 사용하여 문자열로 변환합니다. 자바 스크립트 측면에서 최신 브라우저에서는 JSON을 JSON.parse으로 구문 분석합니다.(이전 버전의 브라우저를 들어, 당신은 당신을 위해 하나를 제공 jQuery를 같이 좋은 라이브러리를 사용하는 또 다른 이유는 페이지,에 JSON 파서를 추가해야합니다.)

다음은 전체 예제 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"를 반환합니다.

+1

좋은 다이어그램. Ajax 요청은 PHP에 관한 일반적인 요청과 거의 같을 것이라고 덧붙이면 좋습니다. 유일한 차이점은 브라우저에서 새 페이지를 표시하는 대신 Javascript에 의해 해고되고 Javascript에 의해 처리된다는 것입니다. (그리고 PHP가 Ajax인지 아닌지를 알고 싶다면이 헤더가 추가됩니다.) – GolezTrol

0

너무 미친 무언가를 필요로하지 돈 있다면 ...
할 수 있습니다 간단한 사전로드, 2 개 필드를 뷰에 접근이 값 확인 및 자바 스크립트를 사용하여 값 전환 :

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

그것을 훨씬 더 좋게 진행될 수 있습니다. 단지 개념을 여기에 보여줍니다.

관련 문제