jQuery.load()
是jQuery提供的一个AJAX方法,用于从服务器加载数据并将返回的HTML放入匹配的元素中。它的基本语法是:
$(selector).load(url, data, callback);
Request.IsAjaxRequest()
是ASP.NET MVC中的一个方法,用于检查当前请求是否是AJAX请求。它主要通过检查HTTP请求头中的X-Requested-With
是否为XMLHttpRequest
来判断。
在ASP.NET MVC2中,jQuery.load()
方法默认不会设置X-Requested-With: XMLHttpRequest
请求头,因此Request.IsAjaxRequest()
会返回false。这与jQuery的其他AJAX方法(如$.ajax()
, $.get()
, $.post()
)不同,后者会自动设置这个请求头。
$.ajax({
url: yourUrl,
type: 'GET',
success: function(data) {
$('#yourElement').html(data);
}
});
$('#yourElement').load(yourUrl, function() {
// 回调函数
}, function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
});
$.fn.ajaxLoad = function(url, data, callback) {
return this.each(function() {
$.ajax({
url: url,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(response) {
$(this).html(response);
if (callback) callback.apply(this, arguments);
}.bind(this)
});
});
};
// 使用方式
$('#yourElement').ajaxLoad(yourUrl);
如果无法修改客户端代码,可以在服务器端修改检查逻辑:
public static bool IsAjaxRequest(this HttpRequestBase request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
// 检查标准AJAX头
if (request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
return true;
}
// 或者检查特定的内容类型
if (request.ContentType == "application/json")
{
return true;
}
// 或者添加其他你需要的检查条件
return false;
}
这个问题主要出现在以下场景:
以上解决方案可以根据你的具体需求选择最适合的一种。
没有搜到相关的文章