Javascript AJAX 请求和普通浏览器请求的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8685750/
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-24 07:05:01  来源:igfitidea点击:

Difference between AJAX request and a regular browser request

javascriptajaxxmlhttprequest

提问by Qqwy

Is there a difference between an AJAX request and a direct browser request (in terms of how a web page is called and loaded)?

AJAX 请求和直接浏览器请求(就网页的调用和加载方式而言)有区别吗?

In other words, I mean: is a direct server-side request handled in any way differently than a client-side request (initiated by the browser)?

换句话说,我的意思是:直接服务器端请求的处理方式是否与客户端请求(由浏览器发起)不同?

采纳答案by Mark Kahn

An AJAX request is identicalto a "normal" browser request as far as the server is concerned other than potentially slightly different HTTP headers. e.g. chrome sends:

就服务器而言,除了可能略有不同的 HTTP 标头之外,AJAX 请求“普通”浏览器请求相同。例如铬发送:

X-Requested-With:XMLHttpRequest

I'm not sure if that header is standardized or not, or if it's different in every browser or even included at allin every browser.

我不知道如果这头标准化与否,或者如果它在每一个浏览器不同,甚至包括所有在每个浏览器。



edit: I take that back, that header is sent by jQuery (and likely other JS libraries), not the browser as is evidenced by:

编辑:我收回这一点,该标头是由 jQuery(可能还有其他 JS 库)发送的,而不是由浏览器发送的,如下所示:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/');
xhr.send();

which sends:

它发送:

Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie: ....
Host:stackoverflow.com
If-Modified-Since:Sat, 31 Dec 2011 01:57:24 GMT
Referer:http://stackoverflow.com/questions/8685750/how-does-an-ajax-request-differ-from-a-normal-browser-request/8685758
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11

which leads me to the conclusion that by defaultthere is absolutely no difference.

这使我得出结论,默认情况下绝对没有区别。

回答by jfriend00

There may be some header differences, but the main behavior difference is on the client.

可能存在一些标头差异,但主要的行为差异在于客户端。

When the browser makes a regular request as in window.location.href = "index.html", it clears the current window and loads the server response into the window.

当浏览器发出常规请求时window.location.href = "index.html",它会清除当前窗口并将服务器响应加载到窗口中。

With an ajax request, the current window/document is unaffected and javascript code can examine the results of the request and do what it wants to with those results (insert HTML dynamically into the page, parse JSON and use it the page logic, parse XML, etc...).

使用 ajax 请求,当前窗口/文档不受影响,javascript 代码可以检查请求的结果并用这些结果做它想做的事情(将 HTML 动态插入页面,解析 JSON 并使用它的页面逻辑,解析 XML , 等等...)。

The server doesn't do anything different - it's just in how the client treats the response from the two requests.

服务器没有做任何不同的事情 - 只是客户端如何处理来自两个请求的响应。

回答by slashCoder

Some popular client-side libraries like jQueryinclude the X-Requested-Withheader in their requests and set it to XMLHttpRequestto mark them as AJAX.

一些流行的客户端库(如jQuery)X-Requested-With在其请求中包含标头并将其设置为XMLHttpRequest以将它们标记为 AJAX。

This seems to have been considered standard enough a few years ago (probably due to the huge popularity of jQuery and its presence in almost every website) that many server-side frameworks even have helpers that take care of checking for this header in the received request for you:

几年前这似乎已经被认为是足够标准的(可能是由于 jQuery 的巨大普及和它在几乎每个网站中的存在),许多服务器端框架甚至有帮助检查接收到的请求中的这个标头为你:

ASP.NET MVC 5:

ASP.NET MVC 5:

HttpRequestBase.IsAjaxRequest()

Django:

姜戈:

HttpRequest.is_ajax()

Flask:

烧瓶:

flask.Request.is_xhr

However, it seems that with the end of jQuery's reign in the front end world and the standardization of the fetchAPI and the rise of other modern client-side libraries that don't add any header for this purpose by default, the pattern has fallen into obsolescence also in the backend; with ASP.NET MVC not including the helper in newer versionsand Flask marking it as deprecated.

然而,随着 jQuery 在前端世界的统治结束、fetchAPI的标准化以及其他默认情况下不为此目的添加任何标头的现代客户端库的兴起,这种模式已经陷入后端也过时了;ASP.NET MVC 不包括新版本中的帮助程序,而 Flask 将其标记为已弃用。

回答by Marcelo Paix?o Resende

I always check if "text/html" is the request's "best" Accept mimetype, because browsers always send that as the first.

我总是检查“text/html”是否是请求的“最佳”接受 mimetype,因为浏览器总是将它作为第一个发送。

Firefox example:

火狐示例:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Of course, this may still be a ajax request with text/html as the Accept mimetype, but I found this to be reliable when you know what client will consume your backend api.

当然,这可能仍然是一个以 text/html 作为 Accept mimetype 的 ajax 请求,但是当您知道哪个客户端将使用您的后端 api 时,我发现这是可靠的。

回答by Lawrence

Although I believe you guys, there is domething totally weird on weblogic: I am writing an app using ExtJS framework which does AJAX calls.

虽然我相信你们,但在 weblogic 上有一些非常奇怪的东西:我正在使用 ExtJS 框架编写一个应用程序,它执行 AJAX 调用。

While doing the j_security_check, I always get errors when doing it the AJAX way: Weblogic says:

在执行 j_security_check 时,我总是在以 AJAX 方式执行时出错:Weblogic 说:

unauthorized: var submitButton = new Ext.Button({
            text: 'Logon',
            formBind: true, //only enabled once the form is valid
            disabled: true,
            handler: function() {                
                Ext.Ajax.request({
                    url: "j_security_check",
                    params: {
                        j_username: dlg.getForm().findField('j_username').getValue(),
                        j_password: dlg.getForm().findField('j_password').getValue()
                    },
                    method: "GET"
                });
            }
        });

This fails.

这失败了。

When I issue this:

当我发出这个:

window.location.href = "j_security_check?j_username=" + dlg.getForm().findField('j_username').getValue() + "&j_password=" + dlg.getForm().findField('j_password').getValue();

It works! Weird.

有用!奇怪的。

回答by Juan Mendes

Not really. Except that most Ajax clients send a X-Requested-With=XMLHttpRequestHTTP header

并不真地。除了大多数 Ajax 客户端发送一个X-Requested-With=XMLHttpRequestHTTP 标头

回答by Mr. BeatMasta

your user-agent, aka browser, sends an XHR header which you can catch from php like this:

您的用户代理,也就是浏览器,会发送一个 XHR 标头,您可以像这样从 php 中捕获它:

$_SERVER['HTTP_X_REQUESTED_WITH']