检测是否为 AJAX 请求。

huangapple go评论68阅读模式
英文:

Detect if is an AJAX requests

问题

如何检测请求是否为 AJAX 请求?

检查以下代码是否适用于所有浏览器:

req.Header.Get("X-Requested-With")
英文:

How can I detect, if a request is an AJAX or not?

Would checking

req.Header.Get("X-Requested-With")

work for all browser?

答案1

得分: 3

很遗憾,“X-Requested-With”并不总是可靠的。如果你控制着发起Ajax请求,你可以使用beforeSend函数来确保设置这个值:

$.ajax({
    url: "http://localhost/url",
    data: { signature: authHeader },
    type: "GET",
    beforeSend: function(xhr){xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest');},
    success: function() { alert('Success!' + authHeader); }
});

然后你可以检查req.Header.Get("X-Requested-With") == 'xmlhttprequest'

英文:

Unfortunately "X-Requested-With" is not always reliable. If you are in control of making the Ajax call you may use the beforeSend function to ensure this is set:

$.ajax({
    url: "http://localhost/url",
    data: { signature: authHeader },
    type: "GET",
    beforeSend: function(xhr){xhr.setRequestHeader('X-Requested-With', 'xmlhttprequest');},
    success: function() { alert('Success!' + authHeader); }
});

You may then check if req.Header.Get("X-Requested-With") == 'xmlhttprequest'

huangapple
  • 本文由 发表于 2015年1月20日 00:06:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/28028830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定