【发布时间】:2016-12-20 19:46:01
【问题描述】:
浏览器必须发送 POST 请求并从 javascript 接收结果 html 页面。 服务器响应中没有 Access-Control-Allow-Origin。服务器无法更改任何内容。
如果人工点击的是提交按钮,则返回响应。
使用 javascript 尝试相同的方法:
$.ajax('https://example.com', {
data:
{
postkey: 'value'
}
method: 'POST',
async: false
})
.done(function (data, textStatus, jqXHR) {
alert(data);
})
.fail(function (xhr, textStatus, errorThrown) {
alert(JSON.stringify(xhr));
});
在 chrome 控制台中返回异常:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52216' is therefore not allowed access.
我也试过jsonp
$.ajax('https://example.com', {
data:
{
postkey: 'value'
}
method: 'POST',
dataType: 'jsonp',
async: false
})
.done(function (data, textStatus, jqXHR) {
alert(data);
})
.fail(function (xhr, textStatus, errorThrown) {
alert(JSON.stringify(xhr));
});
在这种情况下,请求类型更改为 GET 并在 chrome 控制台中出现 stange 错误:
Uncaught SyntaxError: Unexpected token <
Chrome 开发者工具显示在这两种情况下 example.com 服务器都返回了正确的 html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="et">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="content-language" content="et">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
...
如何在客户端解决这个问题?我需要模拟点击表单提交按钮并获取结果html页面。
使用了 Jquery、Bootstrap 3 和 jquery UI。 在服务器 Apache 中,使用 Mono、mod_mono、ASP .NET MVC 4.6。
可以在服务器中创建调用此类请求并返回结果的 MVC 控制器。我正在寻找一种从浏览器中执行此操作的方法,而无需额外的应用程序自己的服务器调用。
** 更新**
从 How do I send a cross-domain POST request via JavaScript?jcubic 答案我找到了样本:
还有一种方法(使用 html5 功能)。您可以使用代理 iframe 托管在另一个域上,您使用 postMessage 将消息发送到 那个 iframe,然后那个 iframe 可以做 POST 请求(在同一个域上)和 postMessage 回复到父窗口。
sender.com 上的父级
var win = $('iframe')[0].contentWindow;
win.postMessage(JSON.stringify({url: "URL", data: {}}),"http://reciver.com");
function get(event) {
if (event.origin === "http://reciver.com") {
// event.data is response from POST
}
}
if (window.addEventListener){
addEventListener("message", get, false)
} else {
attachEvent("onmessage", get)
}
reciver.com 上的 iframe
function listener(event) {
if (event.origin === "http://sender.com") {
var data = JSON.parse(event.data);
$.post(data.url, data.data, function(reponse) {
window.parent.postMessage(reponse, "*");
});
}
}
// don't know if we can use jQuery here
if (window.addEventListener){
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
这在http://www.ajax-cross-origin.com/how.html中也有描述
这适用于当前的浏览器吗?这是否合理? 有没有实现这个的通用方法或插件?
【问题讨论】:
标签: javascript jquery html asp.net ajax