ajax 데이터 전송 방식 인 스 턴 스 상세 설명
비동기 프로그램 에서 정 보 를 보 내 고 받 을 때 흔히 볼 수 있 는 것 은 일반 텍스트 와 XML 을 데이터 형식 으로 선택 할 수 있 습 니 다(jQuery 학습 노트 의 Ajax 용법 실례 상세 설명 참조).현 재 는 JSON(JavaScript Object Notation)이 유행 하고 있 습 니 다.자,다음 예 를 들 어 이 세 가지 데이터 형식 이 ajax 의 비동기 응용 에 있 음 을 설명 합 니 다.
일반 텍스트 방식
1.데이터 전송/수신:
Code is cheap.코드 보기:
testJs.js
//       document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
//    XMLHttpRequest  ,   ajax   
function createXMLHTTP() {
  var xmlHttp = false;
  var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
             "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
             "Microsoft.XMLHTTP"];
  for (var i = 0; i < arrSignatures.length; i++) {
    try {
      xmlHttp = new ActiveXObject(arrSignatures[i]);
      return xmlHttp;
    }
    catch (oError) {
      xmlHttp = false; //ignore
    }
  }
  // throw new Error("MSXML is not installed on your system."); 
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}
var xmlReq = createXMLHTTP();
//   ajax    (                ,       :        test)
function validatePwd(oTxt) {
  var url = "/AjaxOperations.aspx";
  xmlReq.open("post", url, true);
  xmlReq.setRequestHeader("Content-Length", oTxt.value.length + $("txtUserName").value.length);
  xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlReq.onreadystatechange = callBack;
  xmlReq.send("action=chkPwd&userInfos=" + escape(oTxt.value + "/" + $("txtUserName").value)); //     
}
function callBack() {
  if (xmlReq.readyState == 4) {
    if (xmlReq.status == 200) {
      alert(xmlReq.responseText); //     
    }
    else if (xmlReq.status == 404) {
      alert("Requested URL is not found.");
    } else if (xmlReq.status == 403) {
      alert("Access denied.");
    } else
      alert("status is " + xmlReq.status);
  }
}
몇 개의 추가 파일 원본 코드:jsTest.htm
<html>
<head>
<title>js test</title>
  <script src="js/testJs.js" type="text/javascript"></script> 
</head>
<body>
<form id="form1">
<div>
    :<input id="txtUserName" name="txtUserName" type="text" />    :<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div>
</form>
</body>
</html>
AjaxOperations.aspx  
AjaxOperations.aspx.cs
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
  public partial class AjaxOperations : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "chkPwd")
      {
        string responseTxt = "         !";
        string tempStr = Request["userInfos"];
        /*                          ,      */
        if (tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[0] == "test" && tempStr.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[1] == "test")
        {
          responseTxt = "    !";
        }
        Response.Write(responseTxt);
      }
    }
  }
}
 
      ,ctrl+F5,      。
                     。      。
 、XML  
1、  XML  
testJs.js
 
//       document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
//    XMLHttpRequest  ,   ajax   
function createXMLHTTP() {
  var xmlHttp = false;
  var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
             "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
             "Microsoft.XMLHTTP"];
  for (var i = 0; i < arrSignatures.length; i++) {
    try {
      xmlHttp = new ActiveXObject(arrSignatures[i]);
      return xmlHttp;
    }
    catch (oError) {
      xmlHttp = false; //ignore
    }
  }
  // throw new Error("MSXML is not installed on your system."); 
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}
var xmlReq = createXMLHTTP();
//   ajax    (                ,       :        test)
function validatePwd(oTxt) {
  var url = "/AjaxOperations.aspx?action=xmlOp";
  var xmlStr = "<profile>" +
  " <userName>" + escape($("txtUserName").value) + "</userName>" +
  " <userPwd>" + escape($("txtPwd").value) + "</userPwd>" +
  "</profile>";
  xmlReq.open("post", url, true);
  // Tell the server you're sending it XML
  xmlReq.setRequestHeader("Content-Type", "text/xml"); //     
  xmlReq.onreadystatechange = callBack;
  xmlReq.send(xmlStr); //   XML
}
function callBack() {
  if (xmlReq.readyState == 4) {
    if (xmlReq.status == 200) {
      alert(xmlReq.responseText); //     
    }
    else if (xmlReq.status == 404) {
      alert("Requested URL is not found.");
    } else if (xmlReq.status == 403) {
      alert("Access denied.");
    } else
      alert("status is " + xmlReq.status);
  }
}
 
jsTest.htm    ,AjaxOperations.aspx HTML      ,    .CS      :
AjaxOperations.aspx.cs
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace WebTest2008
{
  public partial class AjaxOperations : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "xmlOp") //   xml
      {
        XmlDocument doc = new XmlDocument();
        try
        {
          doc.Load(Request.InputStream); //  xml  (        xml     )
        }
        catch (Exception ex)
        {
          throw ex;
        }
        string responseTxt = "";
        string tempName = doc.SelectSingleNode("profile/userName").InnerText;
        string tempPwd = doc.SelectSingleNode("profile/userPwd").InnerText;
        if (tempName == "test" && tempPwd == "test")
        {
          responseTxt = "    !";
        }
        else responseTxt = "    !";
        Response.Write(responseTxt); //    
      }
    }
  }
}
 
      ,     。
2、  XML  :
    ,    .js              xmlReq.responseText   ,       xmlReq.responseXML  :
testJs.js
 
//       document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
//    XMLHttpRequest  ,   ajax   
function createXMLHTTP() {
  var xmlHttp = false;
  var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
             "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
             "Microsoft.XMLHTTP"];
  for (var i = 0; i < arrSignatures.length; i++) {
    try {
      xmlHttp = new ActiveXObject(arrSignatures[i]);
      return xmlHttp;
      }
    catch (oError) {
      xmlHttp = false; //ignore
    }
  }
  // throw new Error("MSXML is not installed on your system."); 
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}
var xmlReq = createXMLHTTP();
//   ajax    (                ,       :        test)
function validatePwd(oTxt) {
  var url = "/AjaxOperations.aspx?action=xmlOp";
  var xmlStr = "<profile>" +
  " <userName>" + escape($("txtUserName").value) + "</userName>" +
  " <userPwd>" + escape($("txtPwd").value) + "</userPwd>" +
  "</profile>";
  xmlReq.open("post", url, true);
  // Tell the server you're sending it XML
  xmlReq.setRequestHeader("Content-Type", "text/xml");
  xmlReq.onreadystatechange = callBack;
  xmlReq.send(xmlStr); //   XML
}
function callBack() {
  if (xmlReq.readyState == 4) {
    if (xmlReq.status == 200) {
      var xmlDoc = xmlReq.responseXML; //   XML
      //      var nodes = xmlDoc.childNodes;
      //      alert("        : " + xmlDoc.documentElement.tagName);
      //      alert("          : " + xmlDoc.documentElement.childNodes.length);
      alert(xmlDoc.documentElement.childNodes(0).text);
    }
    else if (xmlReq.status == 404) {
      alert("Requested URL is not found.");
    } else if (xmlReq.status == 403) {
      alert("Access denied.");
    } else
      alert("status is " + xmlReq.status);
  }
}
 
  ,jsTest.htm    ,AjaxOperations.aspx HTML      ,    .CS          :
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
namespace WebTest2008
{
  public partial class AjaxOperations : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "xmlOp") //   xml
      {
        XmlDocument doc = new XmlDocument();
        try
        {
          doc.Load(Request.InputStream); //  xml  
        }
        catch (Exception ex)
        {
          throw ex;
        }
        string responseXmlTxt = "";
        string tempName = doc.SelectSingleNode("profile/userName").InnerText;
        string tempPwd = doc.SelectSingleNode("profile/userPwd").InnerText;
        if (tempName == "test" && tempPwd == "test")
        {
          responseXmlTxt = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> <msg>    !</msg>"; //    ,   xml  
        }
        else responseXmlTxt = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><msg>    !</msg>";
        Response.ContentType = ("text/xml;charset=UTF-8"); //        ,              xml  
        Response.Write(responseXmlTxt); //  xml
        Response.End();
      }
    }
  }
}
 
  ,                     ,            。
 、JSON  
json     :
json          , xml   。json JavaScript      ,      JavaScript    json              API     。json          :        “‘  / ' ”  。     “{”(   )  ,“}”(   )  。  “  ”    “:”(  );“‘  / '  ”    “,”(  )  。     :
 
function testJson() {
  //    user(json   ,        js  (  )     )
  var user =
  {
    "username": "jeff wong",
    "age": 25,
    "info": { "tel": "12345678", "cellphone": "13312345678" },
    "address": //   
      [
        { "city": "beijing", "postcode": "101110" },
        { "city": "ny city", "postcode": "911119" }
      ]
  }
  alert(user.username);
  alert(user.age);
  alert(user.info.cellphone);
  alert(user.address[0].city);
  alert(user.address[0].postcode);
  user.username = "xiao wang";
  alert(user.username); 
}
 
             ,        ,      ,         ,   ?                json  。json   json.js ,          json    。    ,(json.js    본 사이트 다운로드。) ,              object.toJSONString()   json  。   :
 
function Car(maker, model, year, color) {
  this.maker = maker;
  this.model = model;
  this.year = year;
  this.color = color;
}
function testJson() {
  var tempCar = new Car("VW", "S", 1999, "yellow");
  alert(tempCar.toJSONString());
}
 
     eval  parseJSON()     json   object:
 
function testJson() {
  var str = '{ "name": "jeff wong", "age": 25,"address":"beijing"}';
  var tempObj = eval('(' + str + ')');
  alert(tempObj.toJSONString()); //  eval  
  var tempObj1 = str.parseJSON();
  alert(tempObj1.toJSONString()); //     parseJSON()  
}
 
  json.js   ,         ,        。     ,       :
ajax  json  /    :
 
//       document.getElementById /document.all
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } }
//    XMLHttpRequest  ,   ajax   
function createXMLHTTP() {
  var xmlHttp = false;
  var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
             "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
             "Microsoft.XMLHTTP"];
  for (var i = 0; i < arrSignatures.length; i++) {
    try {
      xmlHttp = new ActiveXObject(arrSignatures[i]);
      return xmlHttp;
    }
    catch (oError) {
      xmlHttp = false; //ignore
    }
  }
  // throw new Error("MSXML is not installed on your system."); 
  if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}
var xmlReq = createXMLHTTP();
//   ajax    (                ,       :        test)
function validatePwd(oTxt) {
  var url = "/AjaxOperations.aspx?action=jsonOp";
  // JSON     ,                           ,        JSON         。
  var str = '{ "userName":"' + $("txtUserName").value + '", "userPwd": "' + $("txtPwd").value + '"}';
  var jsonStr = str.parseJSON().toJSONString();   // you're sending it JSON
  xmlReq.open("post", url, true);
  xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlReq.onreadystatechange = callBack;
  xmlReq.send("sendStr=" + jsonStr); //   JSON(       JSON)
}
function callBack() {
  if (xmlReq.readyState == 4) {
    if (xmlReq.status == 200) {
      var jsonStr = xmlReq.responseText.parseJSON().toJSONString(); //   json  
      alert(jsonStr);
    }
    else if (xmlReq.status == 404) {
      alert("Requested URL is not found.");
    } else if (xmlReq.status == 403) {
      alert("Access denied.");
    } else
      alert("status is " + xmlReq.status);
  }
}
 
    ,AjaxOperations.aspx html      ,AjaxOperations.aspx.cs        :
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest2008
{
  public partial class AjaxOperations : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(Request["action"]) && Request["action"] == "jsonOp") //   JSON
      {
        string responseJsonTxt = "";
        string tempStr = Request["sendStr"].Trim(new char[] { '{', '}' }); //        JSON          JSON   :Json.Net,      ,  Json.Net
        if (tempStr.Split(new char[] { ',' })[0].Split(new char[] { ':' })[1] == "\"test\"" && tempStr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1] == "\"test\"")
        {
          responseJsonTxt = "{\"msg\":\"    !\"}"; //    
        }
        else responseJsonTxt = "{\"msg\":\"    !\"}";
        Response.Write(responseJsonTxt);
        Response.End();
      }
    }
 
jsTest.html  json.js  (    json.js  ,  js  ),  :
 
<html>
<head>
 <title>js test</title>
 <script src="js/json.js" type="text/javascript"></script>
 <script src="js/testJs.js" type="text/javascript"></script>
</head>
<body>
 <form id="form1">
 <div>
    :<input id="txtUserName" name="txtUserName" type="text" />
    :<input id="txtPwd" name="txtPwd" type="password" onblur="validatePwd(this)" /></div>
 </form>
</body>
</html>
 
         ajax        。
                            
                             
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Javascript Ajax에 대한 간단한 연습저는 약 4년 동안 프로그래밍 개인 튜터로 일한 경험이 있습니다. 약 5년 전에 " "이라는 제목의 페르시아어로 내 웹사이트에 블로그 게시물을 올렸고 사람들이 저에게 전화하기 시작했습니다. 나는 항상 사람들을 가르치...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.