2011-08-03 4 views
0

자바 스크립트 변수에 ajax get 결과를 배치해야합니다.

다음 작품

$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) 
{ 
    $("#divEdit").html(html); 
}); 

이 작동하지 않습니다는

var editHtml = ""; 
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) 
{ 
    editHtml= html; 
}); 
$("#divEdit").html(editHtml); 

나는 그것이 작동시킬 수있는 방법
var editHtml = ""; 
editHtml = $.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) 
{ 
    return html; 
}); 
$("#divEdit").html(editHtml); 

를 시도?

답변

1

,하지만 당신은 당신에게를 제공 이후를 사용하여 시도 할 수 :

이 작업을해야합니다 ajax 요청에 대한보다 세분화 된 접근 방식. success 콜백에서는

$.ajax({ 
    url: '@Url.Action("_Edit", "News", null)/' + guid_News, 
    type: 'GET', 
    //async: false, 
    success: function(data) { 
     $('#divEdit').html(data); 
    } 
}); 

$.ajax 옵션 심지어 @ aroth의 대답에 귀하의 코멘트 당 false로 설정할 수 있습니다 async라는 매개 변수를 받아 들일 수 있습니다.

2

이 작동하지 않는 이유는 :

var editHtml = ""; 
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) 
{ 
    editHtml= html; 
}); 
$("#divEdit").html(editHtml); 

...이 부분은되기 때문에 function closure :

function (html) 
{ 
    editHtml= html; 
} 

즉시 실행되지 않고, 그것의 실행을 차단하지 그 뒤에 오는 진술. 서버가 요청에 대한 응답을 반환 할 때 실행되지만 그때까지는 문이 이미 실행되고 editHtml은 빈 문자열로 설정됩니다. 내가 $.ajax 호출 (그래서 그것을 작동 100 % 확실하지 않다) 내부 @Url.Action를 사용하여 시도 적이

var editHtml = ""; 
$.get('@Url.Action("_Edit", "News", null)/' + guid_News, function (html) { 
    editHtml= html; 
    setDivHtml(); 
}); 

function setDivHtml() { 
    $("#divEdit").html(editHtml); 
} 
+0

변수를 동기식으로 만들고 변수의 값을 가져 오는 방법을 알고 계십니까? –

+1

@Valamas - 예, [jQuery.ajax] 문서를 확인하십시오 (http://api.jquery.com/jQuery.ajax/). '.get()'을'.ajax()'로 바꾸고'async' 옵션을'false'로 설정하면됩니다. – aroth

+0

+1이 왜 작동하지 않는지 설명합니다. – Ahmad

관련 문제