JQuery Ajax 请求:更改用户代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5771878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:47:59  来源:igfitidea点击:

JQuery Ajax Request: Change User-Agent

jqueryajaxuser-agent

提问by theomega

I'm using JQuery to issue a AJAX-Request to my own Webservice. I need to set or modify the User-AgentHTTP-Header for the HTTP-AJAX-Request, how can I do this the easiest way?

我正在使用 JQuery 向我自己的 Web 服务发出 AJAX 请求。我需要User-Agent为 HTTP-AJAX-Request设置或修改HTTP-Header,我怎样才能以最简单的方式做到这一点?

I tried the hint provided by some users to use the setRequestHeaderMethod to set the User-Agent, but this does not work. It does in fact work for other newly created headers (like X-Test-Header) but it does not work for User-Agent.

我尝试了一些用户提供的提示,使用setRequestHeaderMethod设置User-Agent,但这不起作用。它实际上适用于其他新创建的标头(如X-Test-Header),但不适用于User-Agent.

Thanks!

谢谢!

回答by theomega

It is simply impossible, you are not allowed to change the user-agent for XMLHttpRequests. I'm not sure if this is valid for Internet-Explorer, but the w3c specifies here:

这是不可能的,您不能更改 XMLHttpRequests 的用户代理。我不确定这对 Internet-Explorer 是否有效,但 w3c在此处指定:

The setRequestHeader() method

[...]

When the setRequestHeader(header, value) method is invoked, the user agent must run these steps: [...]

Terminate these steps if header is a case-insensitive match for one of the following headers:

[...]

  • User-Agent

setRequestHeader() 方法

[...]

当调用 setRequestHeader(header, value) 方法时,用户代理必须运行以下步骤: [...]

如果标头是以下标头之一的不区分大小写的匹配,则终止这些步骤:

[...]

  • 用户代理

回答by Peter Olson

If you are using jQuery, set the request header in the ajaxSetup.

如果您使用的是 jQuery,请在 ajaxSetup 中设置请求标头。

$.ajaxSetup({
  beforeSend: function(request) {
    request.setRequestHeader("User-Agent","InsertUserAgentStringHere");
  }
});

回答by Lucas

Well, you could always use jQuery to post to a server-side page which then in turn is able to modify the User-Agentheader, and also make a request to the page which would have been directly accessed by jQuery.

好吧,您总是可以使用 jQuery 发布到服务器端页面,然后该页面又可以修改User-Agent标题,并且还可以向 jQuery 直接访问的页面发出请求。