zoukankan      html  css  js  c++  java
  • Ajax请求,跨域小坑

    今天在上班的时候,被坐在旁边项目经理叫过去问了一个Ajax请求跨域的问题,一开始没理解清楚也还有对这个没有理解的透,后面被打击的要死。

    当时的需求是需要测试一个已发布的api接口,需要在本地写测试程序去测试接口。

    当时的看到代码大概是这个样子

    $(document).ready(function () {
    var args = {
    method: "Post",
    url: "Test",
    data: ({ "id": "FB850EE4-48EE-4502-BFE2-736B02899224" })
    // url: "http://xxxxxx/xxxx/api/agency/GetOne",
    };
    $.ajax(args).done(function (data) {
    
    });
    });

    当时我犯的第一个错误,没有理解跨域JSONP的概念

    JSONP使用只能在GET方式下才能生效,dataType修改成post在Jquery也会转成GET方式,然而这个接口不支持GET方式请求。

      var args = {
                method: "POST",
                //  url: "Test",
                dataType: 'JSONP',
                data: ({ "id": "FB850EE4-48EE-4502-BFE2-736B02899224" }),
                url: "http://xxxxxxx/xxxx/api/agency/GetOne",
            };
            $.ajax(args).done(function (data) {
            });

    所以就在后面看到了类似于这样的代码,修改成用WebClient服务器发送POST请求跨域请求的问题。

      public ActionResult Test(string id)
            {
                var url = "http://xxxxxxx/xxxx/api/agency/GetOne";
                System.Net.WebClient wCient = new System.Net.WebClient();
                wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                byte[] postData = System.Text.Encoding.ASCII.GetBytes("id="+ id);
                byte[] responseData = wCient.UploadData(url, "POST", postData);
                string returnStr = System.Text.Encoding.UTF8.GetString(responseData);//返回接受的数据 
                return Json(new {  rows = returnStr }, JsonRequestBehavior.AllowGet);
            }
    

    关于AJAX相关的例子已经很多了,在这里附上一个简单封装过得例子

    base类

    var base = {
        /**
         * 遮罩层加载
         * @returns {} 
         */
        ajaxLoading: function() {
            $("<div class="datagrid-mask"></div>").css({ display: "block",  "100%", height: $(window).height() }).appendTo("body");
            $("<div class="datagrid-mask-msg"></div>").html("正在处理,请稍候...").appendTo("body").css({ display: "block", left: ($(document.body).outerWidth(true) - 190) / 2, top: ($(window).height() - 45) / 2 });
        },
        /**
         * 遮罩层关闭
         * @returns {} 
         */
        ajaxLoadEnd: function() {
            $(".datagrid-mask").remove();
            $(".datagrid-mask-msg").remove();
        },
        /**
         * 
         * @param {} args ajax参数
         * @param {} callback 回调函数
         * @param {} isShowLoading 是否需要加载动态图片
         * @returns {} 
         */
        ajax: function(args, callback, isShowLoading) {
            //采用jquery easyui loading css效果
            if (isShowLoading) {
                base.ajaxLoading();
            }
            args.url = args.url;
            args = $.extend({}, { type: "POST", dataType: "json" }, args);
            $.ajax(args).done(function(data) {
                    if (isShowLoading) {
                        base.ajaxLoadEnd();
                    }
                    if (callback) {
                        callback(data);
                    }
                })
                .fail(function() {
                    if (isShowLoading) {
                        base.ajaxLoadEnd();
                    } else {
                        window.top.topeveryMessage.alert("提示", "操作失败");
                    }
                });
        }
    }

    css

    .datagrid-mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        opacity: 0.3;
        filter: alpha(opacity=30);
        display: none;
    }
    
    .datagrid-mask-msg {
        position: absolute;
        top: 50%;
        margin-top: -20px;
        padding: 10px 5px 10px 30px;
        width: auto;
        height: 40px;
        border-width: 2px;
        border-style: solid;
        display: none;
    }
    
    .datagrid-mask-msg {
        background: #ffffff url('../Img/loading.gif') no-repeat scroll 5px center;
    }
    
    .datagrid-mask {
        background: #ccc;
    }
    
    .datagrid-mask-msg {
        border-color: #D4D4D4;
    }

    方法调用

     base.ajax({
                type: "POST",
                url: "",//url
                contentType: "application/json",
                data: JSON.stringify({})
            }, function(row) {
    });

    总结:沉下心来,不要太浮躁,每天进步一点点是成功的开始!

  • 相关阅读:
    runtime 01-类与对象
    iOS 远程推送的实现
    iOS 选取上传图片界面
    NSAssert
    TableView下拉cell
    此博客主人已搬家访问新家地址:http://write.blog.csdn.net/postlist
    教你如何快速集成第3方
    iPhone应用开发 UITableView学习点滴详解
    苹果Xcode 证书生成、设置、应用完整图文教程
    NSXMLParser解析xml格式
  • 原文地址:https://www.cnblogs.com/wuyongfu/p/7011215.html
Copyright © 2011-2022 走看看