gpt4 book ai didi

javascript - ie/firefox/chrome中jquery调用跨域.net-method

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:36:42 24 4
gpt4 key购买 nike

我一直在尝试通过 JQuery 从另一个域调用 .NET 方法(作为 asmx 文件和普通的 aspx 文件),但我无法在每个浏览器中完成这项工作。目前它在 Firefox 中运行良好,但在 IE 中运行不正常。

function save() {
if (jQuery.browser.msie && window.XDomainRequest) {
// Use XDR
var params = "{'height':" + 10 + ",'width':" + 10 + ",'pos':'" + 10 + "'}";
var xdr = new XDomainRequest();
xdr.onerror = alert_error;
xdr.ontimeout = alert_timeout;
xdr.onprogress = alert_progress;
xdr.onload = alert_loaded;
xdr.timeout = 10000;
xdr.open("post", 'http://domain/reciever.asmx/setdata');
//Tried as webservice and as a normal aspx page
//xdr.open("post", 'http://domain/default.aspx');
xdr.send(params);
}
else {
var params = "pos=" + positions + "&width=" + screenWidth + "&height=" + screenHeight;
var myAjax = new jQuery.ajax(
"http://domain/default.aspx",
{
type: 'post',
cache: false,

crossDomain: true,
data: params
});
}
}

在服务器端,web.config 有:

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>

和网络服务

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string setdata(int width, int height, string pos)

aspx 页面返回:

Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.End();

fiddler 说:Fiddler 在 session #2565 中检测到协议(protocol)违规。内容长度不匹配:请求 header 指示 38 字节,但客户端发送了 0 字节。所以我认为它是“Access-Control-Allow-Origin”,但这是我设置的(至少据我所知)。

谁能帮助我理解我做错了什么。

最佳答案

出于某些安全原因,某些浏览器不允许跨域 Ajax 调用(使用 XmlHttpRequest 对象的调用)。

但是解决方案是使用JSONP 调用而不是ajax 调用。 JSONP 通过发出适合脚本文件的请求来避免这种情况。通过使用 JSONP 发生以下事情使跨域请求成为可能,

1.不是访问 XHR 对象,浏览器首先创建一个新的脚本标记以注入(inject) HTML DOM

2.脚本标签的 URL 设置为您正在查找的 URL 以获取/发布(使用 HTTP GET)数据。

3.页面中注入(inject)了script标签,导致...

4.请求发送到服务器,即使是跨域

5.服务器以JavaScript函数调用的形式返回数据

6.浏览器接收数据并执行函数调用

查看下面的 url 以获取实现细节,

http://www.codeproject.com/Articles/78757/Making-Cross-Domain-jQuery-AJAX-Calls.aspx

http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide

希望这对你有帮助...

关于javascript - ie/firefox/chrome中jquery调用跨域.net-method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6563801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com