asp.net mvc: how to detect when a page is called using ajax

后端 未结 6 1845
遥遥无期
遥遥无期 2021-02-12 20:26

how to detect when a page is called using ajax in asp.net mvc ?

6条回答
  •  隐瞒了意图╮
    2021-02-12 20:53

    There is no specific way to determine if the call was made by javascript or directly in the browser, as it is a regular http call.

    You can add a header to your ajax call to distinguish it from other calls, or possibly add a parameter to the query string that is only used on ajax calls.

    ASP.NET MVC ajax does add such a header - X-Requested-With: XMLHttpRequest, which you can use to sniff that this is an ajax call by the mvc ajax library. However, if you are using jQuery or your own hand rolled ajax calls, this will not be set. Additionally, other clients might spoof this header (using WebClient, for example) so finding it is not a guarantee that an ajax call has been made.

提交回复
热议问题