js ajax 传送xml dom对象到服务器

时间:2021-07-21 17:22:45
客户端代码
1 <script>
var isie = true;
var xmlhttp = null;
function createXMLHTTP() {//创建XMLXMLHttpRequest对象
if (xmlhttp == null) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//if (xmlhttp == null) {
// alert('你的浏览器不支持AJAX');
//}
}
if ($.browser.msie) {//IE浏览器
isie = true;
}
else {
isie = false;
} }
//创建XML文档那个对象,也是第一步
function createDomXml() {
var domXml = null;
//IE浏览器创建xml dom对象
var signs = ["Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "Msxml2.DOMDocument", "Microsoft.XmlDom"];
for (var i = 0; i < signs.length; i++) {
try {
domXml = new ActiveXObject(signs[i]);
break;
}
catch (e) { }
} //其他浏览器
if (domXml == null)
domXml = document.implementation.createDocument("", "", null);
return domXml;
}
//第二步:客户端获取数据写入xml文档对象里
function createXml(dom) {
var root = doc.createElement("root");//创建根结点
var assign_id = doc.createElement("id");//子节点
var assign_ans = doc.createElement("answer");//子节点
if (isie) {
assign_id.text = "1";
assign_ans.text = "1";
}
else {
assign_id.textContent = "1";
assign_ans.textContent = "1";
} root.appendChild(assign_id); root.appendChild(assign_ans); dom.appendChild(choose);
}
function submit() {
var dom = createDomXml();
createXMLHTTP();
if (xmlhttp == null) {
alert("你的浏览器不支持ajax,请换个浏览器试试");
return 0;
}
createXml(dom); xmlhttp.onreadystatechange = success;
xmlhttp.open("post", "test.aspx", true);//接收请求页面
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(dom);
} function success()//异步处理函数,当服务成功返回时
{
if (xmlhttp.readyState == 4) {
alert(xmlhttp.status);
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("test error");
}
}
}
</script>
服务器端代码 
1 protected void Page_Load(object sender, EventArgs e)
{
string res;
Request.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Request.InputStream);
XmlNode node = xmlDoc.SelectSingleNode("choose");
foreach (XmlNode child in node.ChildNodes)
{
res + child.innerText;
}
Response.Write(res);
Response.End();
}
}