利用 iframe解決ajax的跨域問題


問題

 

1. form提交或a標簽跳轉方式提交不會引發跨域問題。

2. ajax出於安全問題就有了跨域問題,因為一次請求中既訪問了外部域最后返回了自己的域。

3. 用iframe其實就是想仿照ajax的效果,把form請求提交到iframe里就不會將當前頁面跳轉,到后台處理業務訪問其他域的資源,然后往頁面回寫JavaScript腳本的方式返回信息。

前台 觸發鏈接

<a class="weui_btn weui_btn_primary" id="toLoan">立即出借</a>

前台 腳本創建form和iframe 然后提交到后台

<script type="text/javascript">
    function smal_send(){
        var  user=$("#name").val();
        var  pwd=$("#pwd").val();
        //http://localhost/juhe/Managers/DB/kuayu.php  你需要提交數據所到的后台地址
        //method="post"則為post方式提交;method="get"則為get方式提交
        var form =$("<form action='../../riskAssessment/checkUserLoan/${bid.id}' method='post'>" +
        "<input type='hidden' name='user_name' value=''/> " +
        "<input type='hidden' name='password' value=''/> " +
        "</form> ");
        $( "#SMAL" ).remove();//如果已存在iframe則將其移除
        $( "body").append("<iframe id='SMAL' name='SMAL' style='display: none'></iframe>");//載入iframe
        (function(){
        $( "#SMAL" ).contents().find('body').html(form);//將form表單塞入iframe;
        $( "#SMAL" ).contents().find("form input[name='user_name']").val(user);//賦值給iframe中表單的文本框中
        $( "#SMAL" ).contents().find("form input[name='password']").val(pwd);//賦值給iframe中表單的文本框中
        $( "#SMAL" ).contents().find('form').submit();//提交數據
        }());
        }
        $(document).ready(function(){
                $("#toLoan").click(function(){
                       smal_send();//調用函數
                })
            })
    </script>

 

后台 業務邏輯是這樣 沒有用戶信息,攔截器攔截去微信服務器獲取openId(跨域),給用戶后台登陸后返回到頁面跳轉的后台鏈接,走后台處理邏輯,返回處理信息結果。

 

/**
     * 校驗用戶是否激活借款身份
     * @param userId
     * @param request
     * @param response
     */
    @RequestMapping("checkUserLoan/{bidId}")
    public String checkUserLoan(HttpServletRequest request,HttpServletResponse response,@PathVariable long bidId){                
        // 當前登錄用戶
        Users currentUser = userService.currentUser(request);        
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out;
        if(currentUser.getBusinessPersonal() > 0){
            try {
                out = response.getWriter();
                out.print("<script>window.parent.location.href=\"../../pay/loan/"+bidId+"\"</script>  ");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                out = response.getWriter();
                out.print("<script>$(window.parent.document).find(\"#errorDialog2\").attr(\"style\",\"display:block;\");</script>");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM