programing

AJAX에서 xml 응답을 구문 분석하는 가장 좋은 방법은 무엇입니까?

css3 2023. 10. 22. 20:20

AJAX에서 xml 응답을 구문 분석하는 가장 좋은 방법은 무엇입니까?

XML로 요청에 응답하는 서버가 있는데 javascript로 파싱하고 싶습니다.저는 사용하기 쉬운 액션스크립트 xml 파서를 정말 좋아합니다.서버에서 가져온 XML을 쉽게 구문 분석할 수 있는 방법이 있습니까?

이상적인 용도는 다음과 같습니다.

fetchXML new XMLParser.parser.parse가 문서에 액세스합니다.

그건 그렇고 저는 jquery를 사용할 계획입니다.

단골손님$.ajax와 함께dataType: "xml"트릭을 수행할 것입니다. 그러면 간단한 웹 페이지처럼 jQuery selector로 컨텐츠를 검색할 수 있습니다(예:attr예제에서 각 북 노드의 "코드" 필드를 검색하는 기능 또는find특정 노드 유형을 찾는 기능).

예를 들어 제목별로 특정 책을 찾을 수 있습니다.

$(xml).find("book[title='Cinderella']")

어디에xml데이터는 다음과 같습니다.success핸들러가 수신합니다.$.ajax.


전체 예시는 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
 <title>jQuery and XML</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta name="language" content="en" />
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body

<div id="output"></div>

<script type="text/javascript">
$(document).ready(function(){
 $.ajax({
  type: "GET",
  dataType: "xml",
  url: "example.xml",
  success: function(xml){
   $(xml).find("book").each(function(){
    $("#output").append($(this).attr("code") + "<br />");
   });
  }
 });
});
</script>


</body>
</html>

일치하는 XML 파일:

<?xml version="1.0" encoding="UTF-8"?> 
<books title="A list of books">
 <book code="abcdef" />
 <book code="ghijklm">
  Some text contents
 </book>
</books>

올바른 컨텐츠 유형으로 데이터를 반환합니다(예:application/xmlXHR이 파싱해 줄 겁니다

참고 항목: jQuery의 ajax 메서드에 대한 dataType 인수.

언급URL : https://stackoverflow.com/questions/3957932/whats-the-best-way-to-parse-xml-response-in-ajax