2014-05-22 4 views
0

테스트 버튼을 클릭하면 결과가 나타나지 않으며 오류도 발생하지 않습니다. 당신이 아마 볼 수 있듯이 나는 자바 스크립트에서 매우 초보자이다. 어떤 솔루션을 권하고 싶습니다. 그래서이 "수업"을 쓸 수 있습니까? 나는 그것이 jQuery ajax와 같이 더 많이 일하기를 원한다. $ .ajax ({}); ... 자바 스크립트 오버라이드 객체 속성

var Ajax = function(){ 

     this.method = null; 
     this.url = null; 
     this.headerType = null; 
     this.data = null; 

     function request (callback) { 
      var xml = new XMLHttpRequest(); 

      xml.open(this.method, this.url, true); 
      xml.setRequestHeader(this.headerType || "Content-type", "application/x-www-form-urlencoded"); 

      xml.onreadystatechange = function() { 
       if(xml.readyState == 4) { 
        if(xml.status == 200) { 
         callback(xml.responseText); 
        } 
       } 
      } 
      xml.send(this.data || null); 
     } 
    } 

document.getElementById('test').addEventListener('click', function() { 
     Ajax({ 
      method : 'GET', 
      url : 'test.php', 
      request : function(response) { 
       document.getElementById('testResult').innerHTML = response; 
      } 
     }); 
    }); 

당신에게

편집 감사합니다 : 여기에 HTML 코드

<button id="test">Get data</button> 
<div id="testResult"></div> 
+0

우리는 HTML 코드를 볼 수 있습니다 자바 스크립트 클래스의

일반 개념이 무엇입니까? 이벤트가 버튼에 올바르게 설정되어 있습니까? – Gwenc37

+2

함수 호출은 마술처럼 객체를 인수로 취해 적용하지 않습니다. 당신은 그것을 코드화해야합니다 ... – epascarello

+0

@ Gwenc37 html을 볼 필요가 없습니다. – epascarello

답변

1

이렇게하면 올바른 방향으로 설정됩니다. 나는 이것을 테스트하지는 않았지만 작동해야한다. 행운을 빈다.

var Ajax = function(options){ 
    var method = options.method || null, 
     url = options.url || null, 
     headerType = options.headerType || null, 
     data = options.data || '', 
     request = options.request || null; // callback function 

    var _request = function(callback) { 
     var xml = new XMLHttpRequest(); 

     xml.open(method, url, true); 
     xml.setRequestHeader(headerType || "Content-type", "application/x-www-form-urlencoded"); 

     xml.onreadystatechange = function() { 
      if(xml.readyState == 4) { 
       if(xml.status == 200) { 
        callback(xml.responseText); 
       } 
      } 
     } 
     xml.send(data || null); 
    } 

    _request(request); 
} 
+0

정말 고마워요. 그것은 매력처럼 작동했습니다. 이제는 @epascarello이 저에게 설명하려고했던 것을 이해합니다. 다양한 솔루션을 제공 한 여러분 모두에게 진심으로 감사드립니다. – lesandru

-1

는 당신이 태그에 onclick을 기능을 시도해 봤어?

<button id="test" onclick="javascript:alert('hello world')"> 

모든 자바 스크립트 함수를 호출 할 수 있습니다.

+0

그건 문제가되지 않습니다. 또한,이 "솔루션"은 [멸시] (http://stackoverflow.com/a/6348597/1048572), [잘못된] (http://stackoverflow.com/q/372159/1048572)이며 잘못되었습니다. 모든 자바 스크립트 함수를 호출하지만 전역 함수는 호출하지 않습니다. – Bergi

1

Ajax() 님의 전화가 무엇인지 이해해야합니다. 속성이있는 {}을 사용하면 함수에 개체 리터럴을 인수로 전달할 수 있습니다. 따라서 함수 내부에 인수를 캡처하고 속성을 설정하는 코드가 필요합니다.

일단 인수와 옵션을 캡처하면 request() 함수를 호출하고 콜백 옵션을 전달해야합니다.

당신이 (글로벌 window.method = null을하고 같은 당신의 변수를 만들 것입니다 이후에 따라서는 window 객체를 참조, 어떤 상황으로 함수를 호출하지 않기 때문에 기능에 this의 사용이 잘못되었습니다.

var Ajax = function(customOptions){ 

     var options = { 
      method : null, 
      url : null, 
      headerType : null, 
      data : null, 
      request : function(){ } 
     }; 

     // override the defaults 
     options = merge_options(options, customOptions); // see note below 

     // call the request() function 
     request(options.request); 

     // modified below to use options.x not this.x 
     function request (callback) { 
      var xml = new XMLHttpRequest(); 

      xml.open(options.method, options.url, true); 
      xml.setRequestHeader(options.headerType || "Content-type", "application/x-www-form-urlencoded"); 

      xml.onreadystatechange = function() { 
       if(xml.readyState == 4) { 
        if(xml.status == 200) { 
         options.callback(xml.responseText); 
        } 
       } 
      } 
      xml.send(options.data || null); 
     } 
    } 

참고 : 위의에서 merge_options() 기능 내장, 당신은 당신이 그것을 사용하려는 경우 포함해야 this answer에서 그 원인을 찾을 수없는

0

음, 하나를합니다. confuguration 객체 f를 취하는 함수 또는 인수 :

function Ajax(config) { 
    if(config==null) 
     ERROR! 
    if(config.method == null) 
     config.method = "GET"; 
    ... check the values and use default or throw errors 
    function request (callback) { 
     var xml = new XMLHttpRequest(); 

     xml.open(config.method, config.url, true); 
     .... and so on 
    } 

} 

아니면 정말 OOP합니다 ('클래스'동일하게 유지하고 다음과 같이 사용)합니다

var ajax = new Ajax(); 
ajax.method = "GET" 
... 
ajax.send(); 

//Only change to the class 
function Ajax() { 
    ... keep the former script 
    this.send = function() { 
     request(); //That is the function you defined, remember? 
    } 

this.send를? 의사 클래스 내에서 varfunction을 사용하여 정의한 모든 항목은 외부에서 액세스 할 수 없으므로

function Class(construct_argument1) { 
    //refference to this for private and anonymous functions 
    var _this = this; //The underscore means nothing. It could be as well 'that' or anything you like 
    var private_variable; 
    function privateMethod() { 
     private_variable = _this.public_variable; 
    } 
    this.publicMethod = function() { 
     alert("Private variable value: "+private_variable); 
    } 
    this.public_variable = null; 
} 
//For classes with many instances, it's good to define methods in prototype 
//These methods, however, have no private access 
Class.prototype.methodThatDoesntEatAllRam = function() {};