2012-02-20 3 views
0

Asp.Net 4.0 Web Forms 및 Jquery 1.6.2 사용. Ajax를 호출하여 페이지의 WebMethod를 호출하고 HTML을 반환하도록하고 싶습니다. 서버 측에서 WebMethod는 다음과 같이 보입니다.Jquery를 사용하여 ASP.Net WebMethod 호출에서 HTML을 반환하는 방법?

[WebMethod] 
public static string GetOrders() 
{ 
    return theMethodThatGeneratesHtml(); 
} 

여기 Ajax 호출 기능이 있습니다.

function GetOrders() 
{ 
    $.ajax({ 
     type: 'POST', 
     contentType: "application/json", 
     url: "Orders.aspx/GetOrders", 
     data: "{}", 
     success: function (data) { 
      $('#content').html(data); 
     }, 
     dataType: "text" 
    }); 
} 

WebMethod에서 반환되는 데이터는 항상 다음과 같이 시작되는 json 개체로 래핑됩니다.

{"d":"\u003ctable\u003e\r\n ........ 

WebMethod에서 HTML 만 반환하도록하려면 어떻게해야합니까?

답변

0

WebMethod는 기본적으로 JSON을 반환합니다. jQuery의 .ajax() 메소드는 반환되는 데이터 유형을 지능적으로 추측합니다.

dataType와 : "HTML"문서의 매개 변수에 대한 참고는 jQuery를이 변환 할 수 있다고 말한다

는 다행히 아약스 방법의 데이터 유형 매개 변수는 어떤 종류의 반환하도록 지시 할 수 있습니다 원하는 경우 다른 유형에 대한 응답의 Content-Type 헤더에 리턴 된 데이터 유형.

dataType와 : 응답의 콘텐츠 형식은 JSON 인 경우이 경우, 당신은 사용하여 변환 할 수 있습니다 "json으로 HTML을"

에 상관없이 내가 할 수있는 데이터 유형을 설정 무엇 http://api.jquery.com/jQuery.ajax/

8

, 그것은 항상 "d"(Here 반환 된 데이터가 항상 광고에 래핑 된 이유에 대한 설명입니다)로 싸서 Json 개체를 반환합니다. 그러나 Json 개체 "d"는 단지 Unicode Escaped html을 찾고 있습니다. Jquery Ajax 호출을 this로 변경해야한다.

function GetOrders() 
{ 
$.ajax({ 
    type: 'POST', 
    contentType: "application/json", 
    url: "Orders.aspx/GetOrders", 
    data: "{}", 
    success: function (data) { 
     $('#content').html(data.d); 
    }, 
    dataType: "json" 
}); 
} 

및 예상대로 작동합니다.

0

jquery mobile을 ASP.Net 웹 양식에 통합 할 때 동일한 시나리오가 발생했습니다. 왜냐하면 복잡한 html 결과를 반환하기 때문입니다. 나는 인코딩 된 html을 서버 측에서 반환하여 문제를 해결할 수있었습니다. 인코딩 된 html은 utf8 형식으로 추가 인코딩됩니다. 이 결과는 div 나 임의의 컨트롤에서 출력을 위해 최종적으로 디코딩됩니다. 이것은 pseuso-코드 :

ASP.NET 출력은 jQuery로 자바 스크립트 섹션에서

dim Result as string=Server.HTMLEncode(htmlouput) 
return Result 

로 반환해야합니다 (비주얼 베이직 스타일, 당신의 선택의 어떤 언어를 사용)

$('#<%=btn.ClientID %>').click(function() {///begin 
       $.ajax({ 
        type: "POST", 
        url: "page.aspx/staticmethod", 
        data: "{}", 
        contentType: "application/json; charset=utf-8", 
        dataType: "html", 
        success: function(html) { 
         try { 
          var out = encode_utf8(html); 
          $('#result').html(htmlDecode(encode_utf8(html))); 
         } catch (ex) { 
          alert(ex); 
         } 
        }, 
        error: function(msg) { 
         //alert error 
        } 
       }) 
       return false; 
      }); //ends 

      //decode html 
      function htmlDecode(value) { 
       if (value) { 
        return $('<div />').html(value).text(); 
       } else { 
        return ''; 
       } 
      } 
      //remove the 'd' encapsulator and other unwanted characters 
     function removedencapsulator(value) { 
      return value.replace('{"d":"', '').replace('"}', '').replace(/(?:\s+)?   <(?:\s+)?/g, '<').replace(/(?:\s+)?>(?:\s+)?/g, '>').replace(/\s+/g, ' '); 
     } 
     ////replace the quote string in the return query 
     function replacequote(value) { 
      return value.replace('\u0027', ''); 
     } 
     //unescape the utf-8 code 
     function encode_utf8(s) { 
      var normalizedData = replacequote(removedencapsulator(s)); 
      return unescape(encodeURIComponent(normalizedData.toString())); 
     } 

이것이이 질문을 해결하기를 바랍니다.

0

대답은 간단한 한 줄의 변화 : JQuery와 HTML로 디코딩을 일으키는 페이지에 추가되지 있지 않은 새로운 요소의 innerHTML 설정

success: function (data) 
    { 
    var decoded = $('<div/>').html(data.d).text(); //here you go 
    $('#content').html(decoded); 
    } 

,는 .text로 다시 밖으로 뽑아().

.

관련 문제