Development Tip

jQuery getJSON 결과를 변수에 저장

yourdevel 2020. 11. 8. 11:23
반응형

jQuery getJSON 결과를 변수에 저장


이 질문에 이미 답변이 있습니다.

getJSON을 사용하여 웹 사이트에서 JSON을 요청합니다. 잘 작동하지만 출력을 다음과 같이 다른 변수에 저장해야합니다.

var myjson= $.getJSON("http://127.0.0.1:8080/horizon-update", function(json) {

                 });

결과를 저장해야하는 myjson데이 구문이 올바르지 않은 것 같습니다. 어떤 아이디어?


을 호출 할 때 값을 얻을 수 없으며 getJSON응답 후에 만 얻을 수 있습니다 .

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

$ .getJSon은 콜백 함수에 콜백 함수를 전달하거나 콜백 함수에서 전역 변수에 할당 할 것을 예상합니다.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO가 가장 좋은 방법은 콜백 함수를 호출하는 것입니다. 그것은 눈, 가독성 측면에 더 좋습니다.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

참고 URL : https://stackoverflow.com/questions/15764844/jquery-getjson-save-result-into-variable

반응형