今天我们的web技术已经相当的完善, 各种前端框架如jquery或者再深一点的工具APIcloud 的使用极大的方便了我们的开发工作.

今天我要分享一个纯javascript的方式来解决请求服务器数据或者异步请求数据来交互的方式.

因为我们的项目前端是ThunderAPP开发的android和IOS移动客户端, 使用完全封闭的APIcloud, 请求的形式都是AJAX

api.ajax({
url : urlConstant.baseUrl + urlConstant.getUserMsgUrl + '?userId='
+ encodeURI(sellerId),
method : 'get',
timeout : 30,
dataType : 'json',
returnAll : false,
}, function(ret, err) {
if (ret) {
if (ret.status == 200) {
$api.byId('userAccount').innerHTML = ret.name;
console.log('@@##sellerAccount=' + ret.name);
} else {
if (ret.info == '获取用户信息失败') {
api.alert({
msg : '卖家的用户名获取失败!'
}, function(ret, err) {
if (ret.buttonIndex == 1) {
api.closeWin();
}
});
} else {
api.alert({
msg : ret.info
});
}
}
} else {
api.alert({
msg : err.msg
});
}
});

接下来我们看一下传统的jquery封闭的ajax:

    $.ajax( {
url : eval(uri).ihv_list,
type : "post",
dataType : "html",
data : "page="+page+"&record="+record+"&"+params+"&orderType="+orderType+"&orderName="+orderName,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success : function(data, textStatus, jqXHR) {
if(jqXHR.status == 0){
alert('Unable to get the data, please check whether the network flow.');
}else{
$('#Searchresult').html(data);
if(type == 1)initPagination($("#page_count").val());
} },
error : function(data, textStatus){
//alert(textStatus);
if("session timeout." == data.responseText){
alert('session timeout.');
}else{
alert(data.responseText);
}
location.href = eval(uri).login_page;
}
});

以上两种封闭的代码只能和以下struts2的action交互:

    public void getGoodsById() throws IOException {
String result = goodsService.getGoodsById(id);
ActionContext context = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
OutputStream out = response.getOutputStream();
out.write(result.getBytes("utf-8"));
out.flush();
out.close();
}

然后我再提供我们的方案, 我们方案的出现是因为现在需要增加后台来管理, 这样我们的局限性在于必须接受服务器返回这种形式的结果,

我放弃了JSP这种服务器动态编译生成的网页返回的形式, 只能通过AJAX请求来完成与服务器的交互.

那么我们无非需要请求数据并且将取得的数据解析并更新到网页上去.

我们只有两个步骤:

1. 创建一个XMLHttpRequest对象, 来为各个需要调用ajax请求的地方提供一个对象可以访问服务器接口.

function MyXMLHttpRequest() {
var xmlhttprequest;
if (window.XMLHttpRequest) {
xmlhttprequest = new XMLHttpRequest();
if (xmlhttprequest.overrideMimeType) {
xmlhttprequest.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
var activeName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
for (var i = 0; i < activeName.length; i++) {
try {
xmlhttprequest = new ActiveXObject(activeName[i]);
break;
} catch (e) { }
}
} if (xmlhttprequest == undefined || xmlhttprequest == null) {
alert("XMLHttpRequest对象创建失败!!");
} else {
this.xmlhttp = xmlhttprequest;
}
} MyXMLHttpRequest.prototype = {
send : function(method, url, data, callback, failback) {
if (this.xmlhttp != undefined && this.xmlhttp != null) {
method = method.toUpperCase();
if (method != "GET" && method != "POST") {
alert("HTTP的请求方法必须为GET或POST!!!");
return;
}
if (url == null || url == undefined) {
alert("HTTP的请求地址必须设置!");
return;
}
var tempxmlhttp = this.xmlhttp;
this.xmlhttp.onreadystatechange = function() {
if (tempxmlhttp.readyState == 4) {
if (tempxmlhttp.status == 200) {
var responseText = tempxmlhttp.responseText;
var responseXML = tempxmlhttp.reponseXML;
if (callback == undefined || callback == null) {
alert("没有设置处理数据正确返回的方法");
alert("返回的数据:" + responseText);
} else {
callback(responseText, responseXML);
}
} else {
if (failback == undefined || failback == null) {
alert("没有设置处理数据返回失败的处理方法!");
alert("HTTP的响应码:" + tempxmlhttp.status
+ ",响应码的文本信息:" + tempxmlhttp.statusText);
} else {
failback(tempxmlhttp.status, tempxmlhttp.statusText);
}
}
}
} //解决缓存的转换
/* if (url.indexOf("?") >= 0) {
url = url + "&t=" + (new Date()).valueOf();
} else {
url = url + "?+=" + (new Date()).valueOf();
}*/ //解决跨域的问题
/*if (url.indexOf("http://") >= 0) {
url.replace("?", "&");
url = "Proxy?url=" + url;
}*/
this.xmlhttp.open(method, url, true); //如果是POST方式,需要设置请求头
if (method == "POST") {
this.xmlhttp.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
}
this.xmlhttp.send(data);
//this.xmlhttp.send(JSON.stringify(data));
} else {
alert("XMLHttpRequest对象创建失败,无法发送数据!");
}
},
abort : function() {
this.xmlhttp.abort();
}, test : function(){
alert("1234");
}
}

包含此对象文件

<script src="javascript/MyXMLHttpRequest.js" type="text/javascript"></script>

调用脚本处:

window.onload = function(){
var submit = document.getElementById('loginSubmit');
submit.onclick = function(){
var name = document.getElementById("loginName").value;
var pwd = document.getElementById("loginPwd").value;
var data = "name=" + name + "&pwd=" + pwd; //此处注意
var request = new MyXMLHttpRequest();
request.send("POST", "login.do",data ,success_callback, error_callback);
}; function success_callback(responseText,responseXML){
var obj = JSON.parse(responseText); //返回的数据
switch(obj.status){
case 200:
document.location.href = "index.jsp";
break;
default:
alert(obj.info);
break; }
};
function error_callback(status, statusText){
alert(status + ", " + statusText);
};
};

关于form表单字段上传到服务器的部分及服务器返回的数据需要特别注意.

关于纯xmlhttprequest请求服务器数据的更多相关文章

  1. Ajax在jQuery中的应用(加载异步数据、请求服务器数据)

    加载异步数据 jQuery中的load()方法 load(url,[data],[callback]) url:被加载的页面地址 [data]:可选项表示发送到服务器的数据,其格式为 key/valu ...

  2. app请求服务器数据方法1-HttpUrlConnection

    1. 实例化URL对象 首先第一步实例化一个URL对象,传入参数为请求的数据的网址. URL url = new URL("http://www.imooc.com/api/teacher? ...

  3. APP请求服务器数据-HttpUrlConnection

    1. 实例化URL对象 首先第一步实例化一个URL对象,传入参数为请求的数据的网址. URL url = new URL("http://www.imooc.com/api/teacher? ...

  4. iOS请求服务器数据去空NSNull

    我们在处理数据库接口的过程中,如果数据中出现null,我们是没法处理的.我在使用NSUserDaults保存后,出现崩溃. null产生原因 null是后台在处理数据的时候,如果没有设置value值, ...

  5. java ajax长连接请求服务器数据

    Servlet 3.0笔记之异步请求Comet推送长轮询(long polling)篇 Comet另一种形式为长轮询(long polling),客户端会与服务器建立一个持久的连接,直到服务器端有数据 ...

  6. 使用ajax()方法加载服务器数据

    使用ajax()方法加载服务器数据 使用ajax()方法是最底层.功能最强大的请求服务器数据的方法,它不仅可以获取服务器返回的数据,还能向服务器发送请求并传递数值,它的调用格式如下: jQuery.a ...

  7. 本地主机作服务器解决AJAX跨域请求访问数据的方法

    近几天学到ajax,想测试一下ajax样例,由于之前在阿里租用的服务器过期了,于是想着让本地主机既做服务器又做客户端,只是简单地测试,应该还行. 于是,下载了xampp,下载网址http://www. ...

  8. ajax 请求二进制流 图片 文件 XMLHttpRequest 请求并处理二进制流数据 之最佳实践

    写在前面 :从提出需求到完美的解决问题,实现过程是曲折的. 需求:在前(web client)后(Restful Service)端完全解耦的模式框架下,webclient需要请求 Service 返 ...

  9. Android(java)学习笔记210:采用post请求提交数据到服务器(qq登录案例)

    1.POST请求:  数据是以流的方式写给服务器 优点:(1)比较安全 (2)长度不限制 缺点:编写代码比较麻烦   2.我们首先在电脑模拟下POST请求访问服务器的场景: 我们修改之前编写的logi ...

随机推荐

  1. 100天搞定机器学习|Day21 Beautiful Soup

    前情回顾 机器学习100天|Day1数据预处理 100天搞定机器学习|Day2简单线性回归分析 100天搞定机器学习|Day3多元线性回归 100天搞定机器学习|Day4-6 逻辑回归 100天搞定机 ...

  2. Cause: java.lang.NumberFormatException: For input string: "D"

    异常:Cause: java.lang.NumberFormatException: For input string: "D" 问题回显: 原因分析:'D'只有1位,被认为是ch ...

  3. 在Win10下,python3和python2同时安装并解决pip共存问题

    前提 本文是在Windows64位系统下进行的,32位系统请下载相应版本的安装包,安装方法类似. 在Win10下,python3和python2同时安装并解决pip共存问题解决: 1.下载python ...

  4. mybatis 源码分析(三)Executor 详解

    本文将主要介绍 Executor 的整体结构和各子类的功能,并对比效率: 一.Executor 主体结构 1. 类结构 executor 的类结构如图所示: 其各自的功能: BaseExecutor: ...

  5. SpringBoot:处理跨域请求

    一.跨域背景 1.1 何为跨域? Url的一般格式: 协议 + 域名(子域名 + 主域名) + 端口号 + 资源地址 示例: https://www.dustyblog.cn:8080/say/Hel ...

  6. MyBatis的parameterType传入参数类型

    在mybatis映射接口的配置中,有select,insert,update,delete等元素都提到了parameterType的用法,parameterType为输入参数,在配置的时候,配置相应的 ...

  7. 回顾js中的cookie/localstorage

    1.首先简单总结下cookie cookie:可以做会话跟踪 特点:      1.大小限制(不能超过4k)      2.每个域下cookie不能超过50个      3.有效期(和设定时间有关), ...

  8. 如何编写高质量的 JS 函数(1) -- 敲山震虎篇

    本文首发于 vivo互联网技术 微信公众号 链接:https://mp.weixin.qq.com/s/7lCK9cHmunvYlbm7Xi7JxQ作者:杨昆 一千个读者,有一千个哈姆雷特. 此系列文 ...

  9. Google Protocol Buffer Basics: C++

    proto文件简介 每个元素上的"= 1","= 2"标记标识该字段在二进制编码中使用的唯一"标记" 每个字段有三个可选修饰符 requir ...

  10. vue父子组件通信高级用法

    vue项目的一大亮点就是组件化.使用组件可以极大地提高项目中代码的复用率,减少代码量.但是使用组件最大的难点就是父子组件之间的通信. 子通信父 父组件 <template> <div ...