英文:
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'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论