0
点赞
收藏
分享

微信扫一扫

将不确定变为确定~开发人员应该明确知道跨域Post的问题

素的盐 2022-08-25 阅读 70

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

从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的问题_表单

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

二 同步跨域

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

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

将不确定变为确定~开发人员应该明确知道跨域Post的问题_html_02

数据库中的信息如下:

将不确定变为确定~开发人员应该明确知道跨域Post的问题_html_03

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

感谢您的阅读!

作者:仓储大叔,张占岭,
荣誉:微软MVP



举报

相关推荐

0 条评论