문제

Drupal을 처음 접하고 Drupal6을 사용하고 있습니다. 입력 필드를 기반으로 데이터베이스에서 직원 세부 정보 세트를 가져 오는 모듈이 있습니다. 제출 버튼은 다음을 호출합니다. 자바 스크립트 기능 에서 emp.js Ajax 호출을 생성하는 파일

 xmlHttpReq.open('GET', "/empfinder.json&dept=" + dept + "&gender=" + gen+ "&age=" + age, true);

호출기를 사용하려고하는 동안 아래처럼 직접 호출하고 새 페이지에 표시됩니다.

http://156.23.12.14/empfinder.json?page=1&dept=ACC&gender=Male&age=34

같은 페이지에 결과를 표시해야합니다. 이를 위해 호출기 호출을 어떻게 수정해야합니까?

도움이 되었습니까?

해결책

'혼자서'를하는 대신 ajax 요청을 할 때 jQuery 유틸리티 기능을 사용하여 인생을 더 쉽게 만들어야합니다. JQuery 라이브러리는 Drupal Core (적어도 Drupal 6의 경우)에 포함되어 있습니다. 문서는 시작할 수 있습니다 jQuery를 사용하여 Drupal의 Ajax에 대한이 게시물.

다른 팁

나는이 주제에 대한 블로그를했다 AJAX 및 PHP를 사용한 JS 아래에 붙여 넣었습니다.

AJAX 및 PHP를 사용한 JS

Drupal은 표준 양식의 일부로 JS와 Ajax를 광범위하게 지원하며 이것이 어떻게 작동하는지 설명하는 자습서가 있습니다. 그러나 JavaScript가 Ad-Hoc 방식으로 Drupal 모듈과 어떻게 통신 할 수 있는지 설명하는 좋은 자습서를 찾을 수 없었습니다. 예를 들어, PHP에서 사용 가능한 상태 정보를 기반으로 임의의 HTML을 수정할 수 있기를 원했습니다. 이 기술은 아래에 나와 있습니다.

이 페이지의 맨 위에는이 테마의 기본적으로 다소 평범한 탭이 있습니다. 현재 선택된 탭이 더 눈에 띄도록 수정하고 싶었습니다. 물론 이것은 CSS만으로 수행 될 수 있지만 CSS만으로는 충분하지 않은 경우이 기술을 개발하고 싶었습니다.

아래는 앞에서 설명한 JS 파일에 직접 추가 할 수있는 JS입니다. 페이지가로드되어 준비 될 때마다 ID 'Main-Menu-Links'로 요소에서 작동하는 jQuery 함수가 있습니다. InnerHTML을 가져 와서 EncodeUricomponent를 사용하여 URL 매개 변수로 전달할 수있는 안전한 문자열로 변환합니다. 탭 중 하나가 매개 변수를 전달하는 URL을 참조하기 때문에이 작업을 수행해야했습니다.

  var xmlhttp;
  var childnodes;
  // Send post to specified url
  function loadXMLDoc(url,cfunc)
  {
     if (window.XMLHttpRequest)
     {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
     }
     else
     {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
     }
     xmlhttp.onreadystatechange=cfunc;
     // alert("loadXMLDoc: " + url);
     xmlhttp.open("POST",url,true);
     xmlhttp.send();
  }
  // AJAX redirect to camr_custom/getvisits with callback function to replace the href
  // with something to disable the link for nodes that have not been visited.
  function getMenuTabs(str)
  {
     loadXMLDoc("?q=flashum_status/get_menu_tabs&block="+str,function()
                {
                   // alert("getMenuTabs status: " + xmlhttp.status + " readyState: " + xmlhttp.readyState);
                   if (xmlhttp.readyState==4 && xmlhttp.status==200)
                   {
                      // alert("getMenuTabs: " + xmlhttp.responseText);
                      data= jQuery.parseJSON('['+xmlhttp.responseText+']')
                      $.each(data,function(){
                         // alert(this['block']);
                         document.getElementById("main-menu-links").innerHTML = this['block'];
                      });
                   }
                });
  }
  // Locate book navigation block and send innerHTML to PHP module
  $('#main-menu-links').ready(function() {
     lis = document.getElementById("main-menu-links").innerHTML;
     // alert("main-menu-links: " + lis);
     // safe encode this block so that it can contain arbitrary urls in the href links
     lis = encodeURIComponent(lis);
     getMenuTabs(lis);
  });

jQuery 함수는 Drupal 모듈에서 Hook_Menu가 캡처 한 URL을 지정하는 AJAX 게시물이 발생하는 LoadXMLDOC를 호출합니다. 또한 매개 변수 CFUNC에 전달되는 콜백 함수를 사용합니다. 반환시, JSON 응답은이를 HTML로 변환하도록 구문 분석되며 원래 InnerHTML로 직접 저장됩니다. 따라서 PHP 모듈이 HTML에 한 모든 일은 원래 HTML을 대체합니다.

PHP쪽에는 먼저 hook_menu의 배열 요소가 있습니다.

  $items['flashum_status/get_menu_tabs'] = array(
    'page callback'     => 'get_menu_tabs',
    'access arguments' => array('access flashum status'),
    'type' => MENU_CALLBACK,
  );

그런 다음 콜백 함수가 아래에 표시됩니다. 먼저 블록 매개 변수를 꺼내서 구문 분석 할 수 있도록 DOM 객체에로드합니다. Simple_html_dom 객체는 SimpleHtmldom 모듈에 의해 제공되므로 설치하고 활성화해야합니다. 관련 라이브러리를 설치하는 것을 잊지 마십시오. 이것은/all/libraries/simplehtmldom/simple_html_dom.php로 끝나야합니다.

function get_menu_tabs() {
   // drupal_set_message(t("get_menu_tabs: @code", array('@code' => print_r(null, TRUE))));
   if (array_key_exists ('block', $_GET)) {
      $block = $_GET['block'];
      // drupal_set_message(t("get_menu_tabs block: @code", array('@code' => print_r($block, TRUE))));

      // Create a DOM object.
      $html_obj = new simple_html_dom();
      // Load HTML from a string.
      $html_obj->load($block);
      // remove href for nodes not yet visited
      $index = 0;
      foreach ($html_obj->find('li') as $li ) {
         $start = strpos($li->innertext, 'href');
         $end   = strpos($li->innertext, '>', $start);
         $start_html = substr($li->innertext, 0, $end);
         $end_html = substr($li->innertext, $end);
         if (strpos($li->innertext, 'active')) {
            $li->innertext = $start_html.' style="color:red;border: solid red;margin-left:5px;margin-right:5px;"'.$end_html;
            // drupal_set_message(t("get_menu_tabs html_obj: @code", array('@code' => print_r($li->innertext, TRUE))));
         }
         else
            $li->innertext = $start_html.' style="color:black;border: solid #777;"'.$end_html;
         $index++;
      }
      $str = $html_obj->save();
      // drupal_set_message(t("get_menu_tabs str: @code", array('@code' => print_r($str, TRUE))));
      // Release resources to avoid memory leak in some versions.
      $html_obj->clear();
      unset($html_obj);

      return drupal_json_output(array('block'=>$str));
   }
}

마지막으로, 탭이 활성인지 아닌지에 따라 변경되는 인라인 CSS 스타일을 추가하는 Li 항목을 통해 루프합니다. 그런 다음 DOM 객체에서 문자열을 생성하고 Drupal_json_output을 통해 json 형식으로 변환합니다. 물론 이것은 JS 콜백 함수에서 수신됩니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top