2013-04-02 6 views
0

내 웹 사이트의 컨텐트를 비동기 적으로 가져오고 싶습니다. 지금은 내 서버에 대한 하나 개 이상의 요청이 내가 다른 함수에 "conntection 물건을"분리해서하는 좋은 것이라고 생각 가지고 :Ajax 요청에 대한 매개 변수로 CallbackFunction 전달하기

function conToServerAsync(url, postParams, func) 
{ 
    var xmlHttp; 
    if(window.XMLHttpRequest) 
    { 
     xmlHttp = new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlHttp.onreadystatechange = func; 
    xmlHttp.open("POST", url, true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlHttp.setRequestHeader("Connection", "close"); 
    xmlHttp.send(postParams); 
} 

지금 내가 같이 "conToServerAsync"기능을 실행이 다른 기능을 가지고 이 :

function findSearchResult(value) 
{ 
    conToServerAsync("Classes/Async/liveSearch.php", "sVal="+value, function() 
    { 
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
    { 
    document.getElementById("searchResult").innerHTML = xmlHttp.responseText; 
    document.getElementById("searchResult").style.border="1px solid #A5ACB2"; 
    } 
    }); 
} 

내 사례에 대해 실제로 흥미로운 점은 모든 항목을 검사하고 전달 된 모든 매개 변수가 유효하다는 것입니다. 그럼 "(conToServerAsync"마지막 매개 변수의 클래스를 부여하는 기능을 할당하려고 ... ","sval이 .. "함수() {...}"에 직접을 onreadystatechange :

... 
xmlHttp.onreadystatechange = function() 
     { 
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
      { 
      document.getElementById("searchResult").innerHTML = xmlHttp.responseText; 
      document.getElementById("searchResult").style.border="1px solid #A5ACB2"; 
      } 
     } 

... 완벽하게 작동합니다. S 오류는 잘못된 방식으로 함수를 전달하는 것과 관련이 있습니다. 제 사례는 구체적입니다. 그것에 대해 나 자신 만의 질문을했습니다.

고맙습니다 응답 :

답변

2

xmlHttp을 콜백에서 사용하려고했지만 범위를 벗어났습니다. 나는 다음과 같은 방법 제안 : 나는 XMLHTTP 개체의 범위에서 콜백 함수를 호출 할 Function.prototype.call를 사용하는 XMLHTTP 래퍼의 내 구현에

function conToServerAsync(url, postParams, func) 
{ 
    var xmlHttp; 
    if(window.XMLHttpRequest) 
    { 
     xmlHttp = new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlHttp.onreadystatechange = function() { 
     if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { 
     func.call(xmlHttp, xmlHttp); 
     } 
    } 
    xmlHttp.open("POST", url, true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlHttp.setRequestHeader("Connection", "close"); 
    xmlHttp.send(postParams); 
} 

function findSearchResult(value) 
{ 
    conToServerAsync("Classes/Async/liveSearch.php", "sVal="+value, function(xhr) 
    { 
    document.getElementById("searchResult").innerHTML = xhr.responseText; 
    document.getElementById("searchResult").style.border="1px solid #A5ACB2"; 
    }); 
} 
+1

하거나 완벽하게'this' – Musa

+0

작품을 사용 : 고맙습니다, 틀림없이 장소에서 this' 내가 그것을 사용할 수있는'사용하지 않는 (내 밤 : – Hans123

+0

@Musa 니스를 만든 두 스타일을 허용하는 코드를 변경). – bfavaretto

1

을, 그래서 당신은 속성에 액세스 키워드 this을 사용할 수 있습니다 그리고 또한 통과 편의상 매개 변수로 responseText.

if(typeof func=="function") 
    func.call(xmlHttp, xmlHttp.responseText); 

은 쉽게 콜백

function callback(response){ 
    alert(response); 
} 

에 응답을 인쇄 할 수 있습니다하지만 당신은 여전히 ​​XMLHTTP 개체의 모든 속성에 액세스 할 수 있습니다

function callback(response){ 
    alert(this.status); //200 
    alert(response); 
} 

전체 코드 :

function conToServerAsync(url, postParams, func){ 

    var xmlHttp; 
    if(window.XMLHttpRequest){ 
     xmlHttp = new XMLHttpRequest(); 
    } 
    else{ 
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlHttp.onreadystatechange = function() { 
     if(xmlHttp.readyState==4 && xmlHttp.status==200){ 
     if(typeof func=="function") 
      func.call(xmlHttp, xmlHttp.responseText); 
     } 
    } 
    xmlHttp.open("POST", url, true); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xmlHttp.setRequestHeader("Connection", "close"); 
    xmlHttp.send(postParams); 
} 

function findSearchResult(value){ 

    conToServerAsync("Classes/Async/liveSearch.php", "sVal="+value, function(response){ 
    document.getElementById("searchResult").innerHTML = response; 
    document.getElementById("searchResult").style.border="1px solid #A5ACB2"; 
    }); 
} 
0

f 당신이 xmlHttp.onreadystatechange에게 건네 준 유엔은 xmlHttp이라는 컨텍스트로 불리며, this을 사용하여 그 객체를 참조 할 수 있습니다.

function findSearchResult(value) 
{ 
    conToServerAsync("Classes/Async/liveSearch.php", "sVal="+value, function() 
    { 
    if(this.readyState == 4 && this.status == 200) 
    { 
    document.getElementById("searchResult").innerHTML = this.responseText; 
    document.getElementById("searchResult").style.border="1px solid #A5ACB2"; 
    } 
    }); 
} 
관련 문제