zoukankan      html  css  js  c++  java
  • 将不确定变为确定~开发人员应该明确知道跨域Post的问题

    注意:这里的跨域指不到同一域名下,包括一级与二级域名,这里也认为不在同域下

    从A网站把信息以Post的方式发送到B网站,这种过程叫做跨域POST,相类的,A网站把B网站的信息获取回来,一般称为跨域GET请求,而对于后者可以通过异步方式实现,在jq里封装了jsonp,用它来实现异步跨域请求;而异步跨域POST是不可以被实现的,下面我们通过实例来说明。

    一 异步跨域

    JS代码用来实现跨域GET和跨域POST,代码如下:(从www.post.com域名下访问二级域成file.post.com)

    <script type="text/javascript">
        $.ajax({
            type: "GET",
            dataType: "jsonp", 
            url: "http://file.post.com/Home/GetInfo",
            success: function (data) {
                alert(data);
            }
        })
    
        $("#btnsubmit").click(function () {
            alert("操作...");
            $.ajax({
                type: "POST",
                url: "http://file.post.com/home/create2",
                data: { commentTitle: $("#CommentTitle").val(), commentInfo: $("#CommentInfo").val() },
                success: function (data) {
                    alert(data);
                }
            })
        });
    </script>

    表单如下:

    <fieldset>
        <legend>Product_Comment</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ProductID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductID)
            @Html.ValidationMessageFor(model => model.ProductID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.UserID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserID)
            @Html.ValidationMessageFor(model => model.UserID)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.CommentTitle)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CommentTitle)
            @Html.ValidationMessageFor(model => model.CommentTitle)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.CommentInfo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CommentInfo)
            @Html.ValidationMessageFor(model => model.CommentInfo)
        </div>
        <p>
            <input type="button" value="Create" id="btnsubmit" />
        </p>
    </fieldset>

    当加载页面后,通过firebug可以看到,使用jsonp的GET请求,返回了正确的信息:

    而请求异步表单提交后,数据库里并没有记录,就是说异步不支持跨域POST

    二 同步跨域

    我们将表单按钮类型改为submit,让表单同步提交到其它域中

    通过实验表明,同步表单的POST操作是可以的,当然这是正常的,向淘宝的支付接口也是通过同步POST来实现的,呵呵!

    数据库中的信息如下:

    恩,现在您应该对跨域POST有一个明确的认识了吧,对于同步表单POST,没有任何问题,而异步的POST,则受到了限制,无论是二级域名还是其它域名都不能进行POST请求的!

    感谢您的阅读!

  • 相关阅读:
    Java反射机制源码分析及知识点总结
    Dubbo admin 在Windows下的安装和服务发现
    Redis知识点总结
    Error:(xx) java: -source 1.5 中不支持
    Java中的线程间通信
    linux主机名显示bogon问题
    Linux(CentOS)上安装Apache Hadoop
    Java虚拟机(JVM)及其体系结构
    在微服务领域中处理分布式事务
    Redis持久化
  • 原文地址:https://www.cnblogs.com/lori/p/2873257.html
Copyright © 2011-2022 走看看