用代理避免ajax跨域请求(手机验证码)

http://wenku.baidu.com/link?url=90oerGKwoYpsenwmAiQQtWtzAKFKYV33Ob8IMtXLtmKDdSdEsuRjVh7WrWrH29wgNTXAtiROvl6HB_049Er3HBpZyE2PhwDAvojzcUhjeqO

1,URL中中文部分编码
2,有&会被截断解决URL参数中带&连接符参数被截断问题
http://jingyan.baidu.com/article/48b37f8d7870df1a6464888d.html
下面举例JS的方法:a=encodeURIComponent(12&34)&b=56尤其适用于用ajax向动态脚本传递的时候。这样,脚本在取参数的时候,就不会被截断了。// NET 编码HttpUtility.UrlEncode(URL);


jsp
<%@ page language="java" pageEncoding="UTF-8" %>
<%
    String webPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    String path = request.getContextPath();
    webPath += path;
%>
<!DOCTYPE html >
<html >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>员福云</title>
    <link href="<%=webPath%>/resourses/css/common.css" rel="stylesheet" type="text/css"/>
    <link href="<%=webPath%>/resourses/css/style.css" rel="stylesheet" type="text/css"/>
     <script src="<%=webPath%>/resourses/js/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="<%=webPath%>/resourses/js/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
    <script src="<%=webPath%>/resourses/js/custome.js" type="text/javascript"></script>
    <script src="<%=webPath%>/resourses/js/jquery.pagination.js" type="text/javascript"></script>
    <script src="<%=webPath%>/resourses/js/pagination-ext.js" type="text/javascript"></script>
</head>
<body>
<div class="main_con">
    <h3 class="rt_cont noPrint"><span>当前位置 : </span><a href="<%=webPath%>/supplier/securityCenter/index.do">绑定手机</a> <input
            type="button" class="btn_fh" value="< 返 回"
            onclick="location.href='<%=webPath%>/supplier/securityCenter/index.do'"/></h3>

    <div class="mc_tent" id="printDiv">
        <div class="con_tent" align="center">
            <table class="feedback">
                <tr align="center">
                    <th colspan="2" class="fbk_th" align="center"><div align="center">我们不会泄露您的手机信息</div></th>
                </tr>
                <tr align="center">
                    <td class="fbk_lf" align="right" width="50%"><div align="right">国家/地区:</div></td>
                    <td align="left" width="50%"><div align="left">
                    <select >
                    <option value="0" selected="selected">===请选择===</option>
                      <option value="zg" >中国</option>
                      <option value="yg" >英国</option>
                      <option value="fg" >法国</option>
                     </select>
                     </div>
                     </td>
                </tr>
                <tr align="center">
                    <td class="fbk_lf" align="right" width="50%"><div align="right">手机号: +86</div></td>
                    <td align="left" width="50%"><div align="left"><input type="text" id="mobile"></div></td>
                </tr>
                <tr align="center" align="center">
                    <td class="fbk_lf" colspan="2" align="center"><div align="center"><input type="button" id="hqyzm" value="免费获取验证码" ></div></td>
                   
                </tr>
                <tr align="center" align="center">
                    <td class="fbk_lf" align="right" width="50%"><div align="right">验证码:</div></td>
                    <td align="left" width="50%"><div align="left"><input type="text" id="yzm"></div></td>
                </tr>
                <tr >
                    <td class="fbk_lf" colspan="2"><div align="center"><input type="button" id="qd" value="确定"></div></td>
                </tr>

            </table>

        </div>
    </div>
</div>
<div class="clear"></div>
<script type="text/javascript" >

$(function() {


var yzdata;
$("#qd").unbind();
$("#qd").bind("click",function() {
var gj= $("select").val();
var mobile =$("#mobile").val();
var yzm = $("#yzm").val();
if(yzdata==yzm){
  eventdata=[];
   eventdata.push({
  mobilePhone:mobile
   });
   var ndata={
  mobilePhone:mobile,
  yzm:yzm
   };
    $.ajax({

            type: "post",
            url: "<%=webPath%>/system/users/savemobile.do",
            data: ndata,
            dataType: "json",
            success: function (data) {
                if (data = 1) {
                alert("绑定成功,谢谢!");
                } else if (data = 0) {
                    alert("操作失败,该记录可能已不存在。");
                } else if (data > 1) {
                    alert("错误,有多条记录被删除。");
                }
            },
            error: function (textStatus) {
                alert("数据加载失败!!!");
            }
});
}else{
alert("请填写正确的信息!");
}
});
var url="http://10.1.67.253:8080/wondersSMS/getToken?sid=yfy&secret=406629b12c904b8c80c0c1263f37cb97";
var a=encodeURIComponent(url);
$("#hqyzm").unbind();
$("#hqyzm").bind("click",function() {
$.ajax({
type:"post",
            url: "<%=webPath%>/system/users/msg.do?url="+a,
            dataType: "json",
            success: function (data) {
                jsonpCallback(data.token);
            },
            error: function (r) {
            console.log(r);
            }
        });

});
function jsonpCallback(token) { 
var mobile =$("#mobile").val();
var taskid=getFormatDate();
yzdata =random();
var content="尊敬的用户您好,您本次的验证码为"+yzdata;
var url="http://10.1.67.253:8080/wondersSMS/sendSMS?content="+encodeURI(content)///url中注意中文部分编码+"&phonelist="+mobile+"&taskId="+taskid+"&token="+token+"&sid=yfy";
        var a=encodeURIComponent(url);
        $.ajax({
type:"post",
            url: "<%=webPath%>/system/users/msg.do?url="+a,
            dataType: "json",
            success: function (data) {
            },
            error: function (r) {
            console.log(r);
            }
        });
    } 

});


function random() {
return Math.round(Math.random()*99999)+100000;
}

function getFormatDate()
{
   var day=new Date();
   var Year=0;
   var Month=0;
   var Day=0;
   var Hour = 0;
   var Minute = 0;
   var Second = 0;
   var CurrentDate="";
   //初始化时间
   Year       = day.getFullYear();
   Month      = day.getMonth()+1;
   Day        = day.getDate();
   Hour       = day.getHours();
   Minute     = day.getMinutes();
   Second     = day.getSeconds();
 
   CurrentDate = Year;
   if (Month >= 10 )
   {
    CurrentDate = CurrentDate + Month ;
   }
   else
   {
    CurrentDate = CurrentDate + "0" + Month;
   }
   if (Day >= 10 )
   {
    CurrentDate = CurrentDate + Day ;
   }
   else
   {
    CurrentDate = CurrentDate + "0" + Day ;
   }
 
   if(Hour >=10)
   {
    CurrentDate = CurrentDate+ Hour ;
   }
   else
   {
    CurrentDate = "0" + Hour ;
   }
   if(Minute >=10)
   {
    CurrentDate = CurrentDate  + Minute ;
   }
   else
   {
    CurrentDate = CurrentDate + "0" + Minute ;
   }    
   if(Second>=10)
   {
    CurrentDate = CurrentDate + Second;
   }
   else
   {
    CurrentDate = CurrentDate + "0" + Second;
   }
   return CurrentDate;
}
</script>
</body>
</html>



java

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;



  @RequestMapping(value = "/savemobile")
    @ResponseBody
    public String saveMobile(@RequestParam(value = "yzm", required = false) String yzm , User user ) {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
        .getAuthentication()
        .getPrincipal();
    User userdata= indexService.getUserByNameAndPwd(userDetails.getUsername(),userDetails.getPassword());
    if(user!=null){
    if(user.getMobilePhone()!=null){
    userdata.setMobilePhone(user.getMobilePhone());
    userdata.setMobileBindState("1");
    Message msg = new Message();
    msg.setContent("尊敬的用户您好,您本次的验证码为"+yzm);
    msg.setReceiverPhone(user.getMobilePhone());
    msg.setSenderFullname(userdata.getUserName());
    msg.setSenderId(userdata.getId());
    msg.setReceiverId(userdata.getId());
    msg.setReceiverFullname(userdata.getUserName());
    msg.setSenderTime(new Date());
    msg.setSendState("1");
    messageService.add(msg);
    int i= userService.edit(userdata);
    return i+"";
    }else{
    return "2";
    }
    }else{
    return "0";
    }
//    System.out.println("111");
    }
    @RequestMapping(value = "/msg")
    @ResponseBody
    public Object msg(@RequestParam(value = "url", required = false) String url) {
    HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(url);//访问域B的链接
HttpResponse responseproxy;
String msg="";
URLEncoder.encode(url);
try {
responseproxy = client.execute(get);
HttpEntity entity = responseproxy.getEntity();
msg=EntityUtils.toString(entity);
System.out.println(msg);
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();


System.out.println("====nihao==");//    System.out.println("111");
return JSONSerializer.toJSON(msg);

    }

你可能感兴趣的:(用代理避免ajax跨域请求(手机验证码))