2011-02-28 9 views
0

자바 스크립트 범위 문제가 있습니다. 응답 텍스트를 ajax 호출에서 가져 와서 전역 변수에 넣으려고합니다. 그런 다음 다른 함수에서 JSON을 처리하면 코드가 작성됩니다.Ajax Javascript 범위 문제

var JSONDATA = "not gatherd"; 
var ajaxCalls = (function(){ 

       var ajaxer = {     

        defaults:{ 
         url:"test.php", 
         DirectHTML: true, 
         element:"#ajaxerizer"    
        },     
        setup:function(setup){    
         var defaulLengther = this.defaults 

         for (var key in defaulLengther) 
         { 
          if(setup.hasOwnProperty(key)) 
          { 
           this.defaults[key] = setup[key]; 

          } 
         } 

         if(this.defaults.DirectHTML === false) 
         { 

          if (window.XMLHttpRequest) { 
           this.ajaxRequester = new XMLHttpRequest(); 
          } 
          if (window.ActiveXObject) { 
           this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP"); 
          } 
          this.ajaxRequester.open('POST', this.defaults.url, true); 
          this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
          this.ajaxRequester.send(); 
         } 
         this.callIt(); 
        },     


        callIt:function(){ 
         if(this.defaults.DirectHTML === true) 
         { 
          $(this.defaults.element).load(this.defaults.url); 
         } 

         if(this.defaults.DirectHTML === false) 
         {  

          this.ajaxRequester.onreadystatechange = function(){ 
           if (this.readyState == 4) { 
            //This is where I have trouble 
            alert(this.responseText); 
            JSONDATA = this.responseText;//This is the data I want to process and use 
            alert(JSONDATA); 
           } 

          } 
         } 

        } 


       } 
       return ajaxer 

      })(); 

다음은 인덱스

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> 
     <script src="simpleHtmlAjax.js"></script> 

    </head> 
    <body> 
     <div id="ajaxerizer"> 
      <script> 
       ajaxCalls.setup({ 
          url:"json.php", 
          DirectHTML: false, 
        }); 
        alert(JSONDATA); 
      </script> 
     </div> 

    </body> 
</html> 

<?php 
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4); 
echo json_encode($json); 
?> 

어떤 도움을 주셔서 감사합니다 JSON 데이터입니다.

+2

현재 문제는 무엇입니까? – Argote

답변

0

이미 HTML에 jQuery가 포함되어 있으므로 jQuery의 AJAX 헬퍼 함수를 ​​사용하여 자동으로 JSON 데이터를 처리하지 않는 이유는 무엇입니까?

$.post("json.php", function (data) { 
    // do something with data, which should be a plain JS object: 
    // {"one":1, "two":2, "three":3, "four":4} 
}, "json"); 
+0

자바 스크립트 작성의 모듈 패턴에 대해 배우기 때문에. 나는 주로 DOM 선택을 위해 jQuery를 사용할 계획이다. –