XML DOM 튜토리얼로그인
XML DOM 튜토리얼
작가:php.cn  업데이트 시간:2022-04-13 15:27:56

DOM XMLHttp요청


XMLHttpRequest 개체


XMLHttpRequest 개체를 사용하면 전체 페이지를 다시 로드하지 않고도 웹 페이지의 일부를 업데이트할 수 있습니다.


XMLHttpRequest 객체

XMLHttpRequest 객체는 서버와 데이터를 교환하기 위해 뒤에서 사용됩니다.

XMLHttpRequest 객체는 개발자의 꿈입니다. 그 이유는 다음과 같습니다.

  • 페이지를 다시 로드하지 않고 웹페이지 업데이트

  • 페이지 로드 후 서버에서 데이터 요청

  • 페이지 로드 후 서버에서 데이터 수신

  • 데이터 보내기 백그라운드에서 서버에


XMLHttpRequest 개체 만들기

모든 최신 브라우저(IE7+, Firefox, Chrome, Safari 및 Opera)에는 XMLHttpRequest 만들기가 있습니다. 물체.

XMLHttpRequest 객체 생성 구문

xmlhttp=new XMLHttpRequest();

이전 버전의 Internet Explorer(IE5 및 IE6)는 ActiveX 객체를 사용합니다.

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

IE5, IE6을 포함한 모든 최신 브라우저를 처리하려면 해당 브라우저가 XMLHttpRequest 개체를 지원하는지 확인하세요. 지원되는 경우 XMLHttpRequest 객체를 생성하고, 그렇지 않은 경우 ActiveX 객체를 생성합니다:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Running Instance»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요



서버에 요청 보내기

서버에 요청을 보내기 위해서는, XMLHttpRequest 객체를 사용합니다. open() 및 send() 메소드:

xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();

방법설명
open(method,url,async)지정 요청 유형, URL, 요청을 비동기식으로 처리해야 하는지 여부.
方法描述
open(method,url,async)规定请求的类型,URL,请求是否应该进行异步处理。

method:请求的类型:GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
send(string)发送请求到服务器。

string:仅用于 POST 请求
<🎜>메서드: 요청 유형: GET 또는 POST <🎜>url: 서버의 파일 위치 <🎜>async< /em >: true(비동기) 또는 false(동기)
send(string)요청을 다음으로 보냅니다. 섬기는 사람. <🎜><🎜>문자열: POST 요청에만 사용됨


GET 또는 POST?

GET은 POST보다 간단하고 빠르며 대부분의 상황에서 사용할 수 있습니다.

단, 다음과 같은 경우에는 항상 POST 요청을 사용하시기 바랍니다.

  • 캐시된 파일이 옵션이 아닌 경우(서버의 파일 또는 데이터베이스 업데이트)

  • 서버로 보내는 데이터의 양이 많음(POST에는 크기 제한이 없음)

  • 사용자 입력 보내기(알 수 없는 문자 포함 가능), POST가 더 강력함 GET 보안보다 더 강력합니다


URL - 서버의 파일

open() 메소드의 url 매개변수는 서버에 있는 파일의 주소입니다. 서버:

xmlhttp.open("GET","xmlhttp_info.txt",true);

파일은 모든 유형의 파일일 수 있습니다(예: .txt 및 .xml) 또는 서버 스크립트 파일(예: 응답을 다시 보내기 전에 서버에서 작업을 수행하는 .html 및 .php).


비동기 - True 또는 False?

요청을 비동기식으로 보내려면 open() 메서드의 async 매개변수를 true로 설정해야 합니다.

xmlhttp.open("GET","xmlhttp_info.txt",true);

비동기 요청 전송은 웹 개발자에게 큰 발전입니다. 서버에서 수행되는 많은 작업에는 시간이 많이 걸립니다.

비동기적으로 전송함으로써 JavaScript는 서버의 응답을 기다릴 필요가 없지만 다음으로 대체할 수 있습니다.

  • 서버의 응답을 기다리는 동안, 다른 스크립트 실행

  • 응답 준비 시 응답 처리


Async=true

비동기 사용 시 =true, 응답이 준비되면 onreadystatechange 이벤트에 지정됩니다. 실행할 함수:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Run Instance»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요.



Async=false

async=false를 사용하려면 변경하세요. open() 메소드의 세 번째 매개변수를 false로 설정:

xmlhttp.open("GET","xmlhttp_info.txt",false);

async=false를 사용하는 것이 좋지만 몇 가지 작은 요청을 처리하는 경우에는 여전히 괜찮습니다.

서버 응답이 준비될 때까지 JavaScript는 계속 실행되지 않는다는 점을 기억하세요. 서버가 사용량이 많거나 느리면 애플리케이션이 중단되거나 중지됩니다.

참고: async=false를 사용할 때는 onreadystatechange를 쓰지 마세요. 함수 - send() 문 뒤에 코드를 배치하세요.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.open("GET","xmlhttp_info.txt",false);
  xmlhttp.send();
  document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Run Instance»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 누르세요



서버 응답

서버로부터 응답을 받으려면 XMLHttpRequest 객체의 responseText 또는 responseXML 속성을 사용하세요.

属性描述
responseText获取响应数据作为字符串
responseXML获取响应数据作为 XML 数据


responseText 속성

서버의 응답이 XML이 아닌 경우 responseText 속성을 사용하세요.

responseText 속성은 응답을 문자열로 반환하므로 그에 따라 사용할 수 있습니다.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

인스턴스 »

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요



responseXML 속성

서버의 응답이 다음과 같은 경우 XML이 아니고 XML 객체로 구문 분석하려면 responseXML 속성을 사용하십시오:

Instance

cd_catalog.xml 파일을 요청하고 응답을 구문 분석하십시오:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
      xmlDoc=xmlhttp.responseXML;
      var txt="";
      x=xmlDoc.getElementsByTagName("ARTIST");
      for (i=0;i<x.length;i++)
        {
        txt=txt + x[i].childNodes[0].nodeValue + "<br>";
        }
      document.getElementById("myDiv").innerHTML=txt;
        }
      }
  xmlhttp.open("GET","cd_catalog.xml",true);
  xmlhttp.send();
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요



onreadystatechange 이벤트

요청이 서버로 전송되면 응답에 따라 어떤 작업을 수행하려고 합니다.

readyState가 변경될 때마다 onreadystatechange 이벤트가 트리거됩니다.

readyState 속성은 XMLHttpRequest의 상태를 보유합니다.

XMLHttpRequest 객체의 세 가지 중요한 속성:

속성설명
onreadystatechange저장 함수(또는 함수 이름) ReadyState 속성이 변경될 때마다 자동으로 호출됩니다.
readyStateXMLHttpRequest의 상태를 저장합니다. 0에서 4로 변경:
属性描述
onreadystatechange存储函数(或函数的名称)在每次 readyState 属性变化时被自动调用
readyState存放了 XMLHttpRequest 的状态。从 0 到 4 变化:
0:请求未初始化
1:服务器建立连接
2:收到的请求
3:处理请求
4:请求完成和响应准备就绪
status200:"OK"
404:找不到页面
0: 요청이 초기화되지 않았습니다. <🎜> 1: 서버가 연결을 설정합니다 <🎜> 2: 요청 접수됨 <🎜> 3: 요청 처리 <🎜> 4: 요청 완료 및 응답 준비
상태200: "확인" <🎜> 404: 페이지를 찾을 수 없습니다

onreadystatechange 이벤트에서는 서버의 응답을 처리할 준비가 되었을 때 어떤 일이 발생하는지 지정합니다.

readyState가 4이거나 상태가 200인 경우 응답 준비:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요

참고: readyState가 변경될 때마다 onreadystatechange 이벤트가 총 4번 트리거됩니다.


tryitimg.gif추가 예시


getAllResponseHeaders()를 통해 헤더 정보 검색
리소스(파일) 검색 헤더 정보.

인스턴스

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getAllResponseHeaders() function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get header information</button>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


getResponseHeader()를 통해 지정된 헤더 정보를 가져옵니다.
리소스(파일)의 지정된 헤더 정보를 가져옵니다.

인스턴스

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified');
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get "Last-Modified" information</button>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


ASP 파일의 내용 검색
사용자가 입력 필드에 문자를 입력할 때 웹 페이지가 웹 서버와 통신하는 방법.

인스턴스

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


데이터베이스에서 콘텐츠 검색
웹페이지가 XMLHttpRequest 객체를 통해 데이터베이스에서 정보를 추출하는 방법.

인스턴스

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form action=""> 
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


XML 파일의 콘텐츠 검색
XMLHttpRequest를 생성하여 XML 파일에서 데이터를 검색하고 HTML 테이블에 데이터를 표시합니다.

인스턴스

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
    x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
    for (i=0;i<x.length;i++)
      {
      txt=txt + "<tr>";
      xx=x[i].getElementsByTagName("TITLE");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      xx=x[i].getElementsByTagName("ARTIST");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      txt=txt + "</tr>";
      }
    txt=txt + "</table>";
    document.getElementById('txtCDInfo').innerHTML=txt;
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="txtCDInfo">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>

</body>
</html>

인스턴스 실행»

온라인 인스턴스를 보려면 "인스턴스 실행" 버튼을 클릭하세요


PHP 중국어 웹사이트