programing

Ajax/jquery 호출의 성공 함수 외부 변수 사용

javaba 2023. 8. 17. 23:40
반응형

Ajax/jquery 호출의 성공 함수 외부 변수 사용

다음 코드를 가지고 있습니다.

var test;

 $.ajax({
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});

Validate.fail(test);

이제 테스트 var는 콘솔에서 말하는 것처럼 거짓의 true를 제공해야 합니다.하지만 테스트 바는 나에게 왜 정의되지 않은 이유를 줍니다.

 var test; // <-- (1) This code runs first  
 $.ajax({  // <-- (2) Then this runs  
    type: "GET",
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg); //<-- (4) Finally this is run. IF your request is a success 
        test = msg; 
    },
 });
 Validate.fail(test); // <-- (3) This runs third  

코드가 실행되는 순서를 확인합니다.콜백을 통해 코드가 트리거될 때 실행 중이므로 변수를 사용할 수 없습니다.

Validate.fail(test)이 비동기 호출 직후에 발생하기 때문일 수 있습니다.비동기식이라는 것을 기억하세요. 즉, 페이지에서 실행되는 Javascript와 병렬로 실행됩니다.

var test;
 $.ajax({
    type: "GET",
    async: false,
    url: "../views/person/controller.php?actor=person&action=checkAge",
    data: "age=" + value,
    success: function(msg){
        console.log(msg);
        test = msg; 
    },
});
Validate.fail(test);

//jax 함수를 동기화하고 json 매개 변수 "async: false"를 설정하여 javascript는 테스트에 값이 할당될 때까지 기다려야 합니다.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var xm;

  $("#txt").ajaxComplete(function(){
    $('#txt').html(xm);
  });

  $("button").click(function(){

    $.ajax({
      url: 'DBresult_load.php',
      dataType: 'html',
      data: { },                 //you can pass values here
      success: function(result) {xm =result;}
    });
  });


});
</script>
</head>
<body>

<div id="txt"><h2>Let AJAX change this text</h2></div>
<button>Change Content</button>
</body>
</html>

다음은 Ajax 요청에서 변수로 값을 전달하는 솔루션입니다.이게 도움이 되길 바랍니다.

"var"를 선언할 때 "test"라는 용어 앞에서 제거하면 어떻게 됩니까?

콜백 기능이 몇 가지 확장된 방법으로 포장되어 있기 때문에 jQuery로 어떻게 처리되는지 잘 모르겠습니다.하지만 내가 떠나는 이유는 선언문에서 다양합니다.test변수는 입니다.var범위에 상대적인 테스트를 할당합니다.콜백이 특정한 방식으로 처리되는 경우 다음과 같은 범위를 잃을 수 있습니다.test정의됩니다.당신은 그것을 떨어뜨리는 것이 좋을 것입니다.var할당하고 전역 변수로 남겨둡니다.아마 이것이 그것을 보이게 할 것입니다.

편집: 비동기 요청 후 함수 호출 내에서 용어를 참조하고 있는지 몰랐습니다. 콜백 내에 마지막 문을 포함하는 것이 좋습니다.

:)

언급URL : https://stackoverflow.com/questions/5935968/use-variable-outside-the-success-function-from-an-ajax-jquery-call

반응형