JQuery版本的ajax请求:(包括处理WebService中xml字符串)
1 $.ajax({ 2 type: "POST", 3 async: true, 4 url: "", 5 data: "", 6 success: function (data) { 7 data = data.replace("<string xmlns="http://tempuri.org/">", "").
replace("<?xml version="1.0" encoding="utf-8"?>").
replace("</string>", "").replace("undefined", "").
replace(";", "").replace(/</g, '<').
replace(/>/g, '>').replace("<", "<").
replace(/&/g, "&").replace(/&/g, "&").
replace(/ /g, "").
replace(/ /g, ""); 8 9 }, 10 error: function () { 11 12 }, 13 dataType: "html" 14 });
Js版本的ajax请求:
common.js
//由于浏览器版本不同影响Ajax不同,所以遇到不同的版本需要new不同的Ajax //创建一个Ajax对象 function createXmlHttp() { var xhobj = false; try { xhobj = new ActiveXObject("Msxml2.XMLHTTP"); // ie msxml3.0+ } catch (e) { try { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); //ie msxml2.6 } catch (e2) { xhobj = false; } } if (!xhobj && typeof XMLHttpRequest != 'undefined') {// Firefox, Opera 8.0+, Safari xhobj = new XMLHttpRequest(); } return xhobj; }
正文:
get提交:
<!--引进来Common.js -->
<script src="Scripts/Common.js" type="text/javascript"></script>
<script type= "text/javascript">
var aj = false;
window.onload = function () {
//new一个Ajax
aj = createXmlHttp();
}
//Ajax函数 GET提交
function doAjax() {
//打开连接
//需要使用多个参数,第一个设置方法属性,第二个设置目标URL,第三个指定是同步(false)还是异步(true)发送请求
var url = "";
aj.open("GET", url, true);
//设置回调函数[即:需要接受服务器返回的值]
//读取状态改变
aj.onreadystatechange = function () {
alert(aj.readyState);
if (aj.readyState >= 4) {
if (aj.status == 200) {//状态码为200正常响应
} else {
}
}
};
//发送[get发送为空]
aj.send(null);
}
</script>
post提交:
<script src="Scripts/Common.js" type="text/javascript"></script>
<script type="text/jscript" >
var aj = false;
window.onload = function () {
aj = createXmlHttp();
}
//Ajax函数 Post提交
function doAjax() {
var url = "Js_Login.aspx";
//如果提交的值是中文,需要编码
//encodeURI() 或 encodeURIComponent()
var user = encodeURI(gel("txt").value);
var pwd = gel("pwd").value;
var data = "user=" + user + "&pwd=" + pwd;
//打开连接
aj.open("POST", url, true);
//需要设定请求头
aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//回调函数
aj.onreadystatechange = function () {
if (aj.readyState >= 4) {
if (aj.status == 200) { //状态码为200正常响应
var txt = aj.responseText; //接受数据
}
else {
}
}
}
//发送数据[Post发送不能为空]
aj.send(data);
}
</script>