研究mui的时候测试ajax,发现默认跨域访问是被拒绝的。但提示比较模糊,就在web服务端和客户端都加了有关Access-Control-Allow-Origin和Access-Control-Allow-Headers的配置,在几个浏览器中测试通过。网上有说需要配置客户端、配置浏览器的,也有说只需要配置服务端即可。经过测试得出结论:
配置服务端就可以了。我是用asp.net做的webserver服务,在web.config文件中的<system.webServer>节点内加入配置项:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="X-Requested-With" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
服务端ashx源码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication3
{
/// <summary>
/// login 的摘要说明
/// </summary>
public class login : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain;charset=utf-8";
//context.Response.Headers.Add("Access-Control-Allow-Origin","*");
//context.Response.Headers.Add("Access-Control-Allow-Headers","X-Requested-With");
context.Response.Headers.Add("Cache-Control","no-cache");
string userid = string.Empty;
if (context.Request.Params["userid"] != null)
userid = context.Request.Params["userid"].ToString();
string password = string.Empty;
if (context.Request.Params["password"] != null)
password = context.Request.Params["password"].ToString();
string result = string.Empty;
if (userid.Equals(string.Empty) || password.Equals(string.Empty) || !userid.Equals(password))
{
result = "{\"result\":\"error\",\"userid\":\"\",\"roleid\":\"\"}";
}
else
{
result = "{\"result\":\"ok\",\"userid\":\""+ userid +"\",\"roleid\":\"1001\"}";
}
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
客户端调用界面源码:
<!doctype html>
<html>
<head>
<Meta charset="UTF-8">
<title></title>
<Meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link href="css/mui.min.css" rel="stylesheet" />
</head>
<body>
<button id="btnLogin" type="button" class="mui-btn mui-btn-blue mui-btn-block">按钮</button>
<script src="js/mui.min.js"></script>
<script type="text/javascript">
mui.init();
mui.ready(function(){
var btnLogin = document.getElementById("btnLogin");
btnLogin.onclick=function(){
var url = "http://localhost:1664/login.ashx";
mui.ajax(url,{
data:{
userid:1,
password:1
},
type:"get",
dataType:"json",
success: function(data){
mui.alert("ok");
},
error:function(){
mui.alert("error");
}
});
};
});
</script>
</body>
</html>
这里客户端使用hbuilder编写的,利用其代码块快捷键,可以瞬间构造出一个漂亮的界面,非常赞的开发工具。这里已经将调试ajax的障碍清除了,后续继续研究使用html5开发app的相关内容。
原文链接:https://www.f2er.com/ajax/161531.html