2010-06-23 4 views
5
$(document).ready(function(){ 
//global vars 
var name = $("#username"); 
    var email = $("#email"); 


function usernameExists() { 
    $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) { 
     if(m==1) { 
    return false; 
    } else { 
    return true; 
    } 
    }); 
} 
}); 

이 함수가 호출 될 때 Firebug는 올바른 응답을 표시하지만 아무 것도 반환하지 않습니다. (이 $ .get (...) 함수는 함수 외부에서 테스트되었습니다. usernameExists()하지만 반환하지 않고 완벽하게 작동).jQuery는 true/false를 반환하는 함수를 얻습니다.

문제 어떻게 해결하는 방법은 무엇입니까?


 $(document).ready(function(){ 
    //global vars 
    var form = $("#register"); 
    var name = $("#username"); 
    var email = $("#email"); 

    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
       if(m==1) { 
        form.submit(function(){ return false; }); 
       } else { 
        form.submit(function(){ 
     if(validateName() & validateEmail() & validatePass1() & validatePass2()) 
      return true 
     else 
      return false; 
       }); 
      } 

     } 
    ); 

function validateName(){ 
     // some check here 
    } 

// and other functions 

}); 

답변

8

당신은 아무것도 반환하지 않습니다 호출하고 함수입니다.

$.get()에서 응답을 반환하려고 했더라도 호출이 비동기 적이기 때문에 응답이 수신 될 때까지 반환 값을 사용했을 코드가 이미있을 가능성이 높습니다 실행. 당신이해야 할 일은

$.get() 콜백 내에서 코드를 호출 할 수 있습니다.

function usernameExists() { 
    $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) { 
      someOtherFunction(m==1); 
    }); 
} 

function someOtherFunction(parameter) { 
    // The parameter will be true or false 
    // depending on the value of m==1 
} 

는 귀하의 의견에 따라 업데이트되었습니다.

$.get()submit()에 가져 오는 것이 더 좋을지 만 원래 생각대로 유지하는 것이 좋습니다.

자바 스크립트 코드가 정상적으로 실행 동기 비동기 대 동기 스크립트의 기쁨

form.submit(function(){ 
     // After usernameExists() is called, we need to hand off 
     // the rest of the execution to that function since 
     // this one will be done executing before the get() 
     // response is received 
    usernameExists(); 
    return false; 
}); 

function usernameExists() { 
    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
       if(m==1) { 
        // do something if true 
       } else { 
        // do something if false 
       } 
      } 
    ); 
} 

설명. 즉, 한 번에 한 행을 실행하거나 다음 행이 실행되기 전에 한 행이 실행을 완료해야합니다.

var greeting = "hi there"; // set the greeting variable 

alert(greeting); // the alert won't fire, 
        // until the previous line finished successfully 

이렇게하면 상황이 매우 훌륭하고 예측 가능합니다. 그러나 그 규칙에는 몇 가지 예외가 있습니다. 한 가지 주목할만한 예외는 AJAX 호출입니다.

$.get()은 AJAX 호출의 예입니다. AJAX의 "A"는 비동기를 의미하며, 이는 다음 코드 행이 실행되는 것을 막지 못함을 의미합니다.

분파는 완료 (예를 들어) 1 초가 소요 $.get()을 할 때 $.get() 오랫동안 이후 $.get()가 응답을받은 시간 종료 후, 어떤 코드가 온 것입니다.

이전의 greeting 예제를 사용하지만 이번에는 AJAX를 사용합니다. $.get() 응답이 수신되기 전에 그는 $.get() 비동기이며, 그것의 데이터를 기다리는 동안 실행 체인을 일시 정지하지 않기 때문에

var greeting; // will hold the response from our AJAX call 

$.get('some/path/to/data.php', 
     function(m) { 
      greeting = m; // populate the greeting variable with the data returned 
     } 
); 

alert(greeting); // Will alert "undefined" instead of the data that was returned 
        // because the $.get() code above is asynchronous, which allows 
        // the code below it (the alert in this case) to continue 
        // executing. 

당신이 볼 수 있듯이

alert(greeting)는 오랫동안 실행했을 것이다.

는 응답이 수신 될 때까지 실행되지 않도록 당신의 alert()$.get()에 대한 콜백 내부에 놓여지는,이 문제를 해결하려면.

var greeting; // will hold the response from our AJAX call 

$.get('some/path/to/data.php', 
     function(m) { 
      greeting = m; // populate the greeting variable with the data returned 
      alert(greeting); // Now the alert will give the expected result 
           // because it is in the callback. 
     } 
); 

결말은 당신의 코드에서, 당신은 $.get(), 콜백 내에서 장소 을해야받은 응답에 의존하는 나머지 코드를 호출하면.

(I 내 원래의 대답했던 것처럼) 콜백 에서 콜백 내에서 호출되는 고유의 기능에 배치하는 것입니다 외부 코드 를 배치 할 수있는 유일한 방법. 코드가 작동하는 방법의


기본 레이아웃 :

당신이 반드시 usernameExists()에 대해 별도의 기능을 필요로하지 않는다는 것을 명심하십시오. 당신은 모든 코드 submit()

form.submit(function() { 
     // Check to make sure input is valid **before** you send the AJAX 
    if(validateName() & validateEmail() & validatePass1() & validatePass2()) { 
     usernameExists(); // If valid, continue with the usernameExists() 
    } 
    return false; // We return false whether or not the content was valid, 
        // in order to prevent the form from submitting prematurely 
}); 

function usernameExists() { 
    $.get("register.php", 
      { check: 1, username: name.val(), email: email.val() }, 

       // Have this callback take care of the rest of the submit() 
      function(m) { 
        // If "m" is less than one, there were no existing users 
        // so we can go ahead and post the data to the server 
       if(parseInt(m) < 1) { 
        // Here, you would need to manually do a post to 
        // submit the data to the server 
        $.post(url, data, callback, datatype); 
       } 
      } 
    ); 
} 

http://api.jquery.com/jquery.post/

+1

@cthulhu 내부에 배치 할 수 있습니다 - usernameExists()가'아무것도 반환하지 않습니다 '때문이 작동하지 않습니다. 그리고 이벤트가 발생했다면,'submit()'의'if()'문은 응답이 수신되기 전에 실행이 완료됩니다. 기본적으로, 당신이해야 할 일은 콜백 내에서'$ .get()'의 응답에 의존하는 모든 * 코드를 유지하는 것입니다. 또는 내 대답처럼 콜백 내부에서 다른 함수를 호출하십시오. 내 대답을 다른 해결책으로 업데이트하겠습니다. – user113716

+0

@cthulhu - 이해해야 할 것은 * usernameExists() 함수에서 값을 반환하려고 시도해서는 안됩니다. 그것은 단순히 작동하지 않습니다. 이 함수의 나머지 코드 실행 *을 수행해야합니다. 그 이유를 이해하지 못한다면 알려주세요. 나는 더 잘 설명 할 수있는 다른 예를 드리겠습니다. – user113716

+0

@cthulhu - 문제 없습니다. : o) 문제를보다 완전하게 설명하는 예제를 통해 몇 분 안에 답변을 업데이트하겠습니다. – user113716

관련 문제