我有以下WebMethod: -
[WebMethod(EnableSession = true)]
public static void OpenReport(string reportName)
{
Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);
if (report != null) reportUrl = report.Url;
}
现在我希望传递report.Url到这个Jquery方法: -
$('.ReportButton').click(function () {
var args = { reportName : '' };
$.ajax({
type: "POST",
url: "ReportsByQuestionsDetails.aspx/OpenReport",
data: JSON.stringify(args),
contentType: "application/json;charset=utf-8;",
success: function (data) {
alert('success');
document.location.href = reportUrl;
},
error: function () {
}
});
});
如何将reportUrl从WebMethod传递给Jquery?
感谢您的帮助和时间
答案 0 :(得分:5)
您需要返回 C#方法中的string
:
[WebMethod(EnableSession = true)]
public static string OpenReport(string reportName)
{
string reportUrl = string.Empty;
Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);
if (report != null) reportUrl = report.Url;
return reportUrl;
}
然后在你的ajax返回Url中你可以做(你可能希望在报告为null时回退):
success: function (data) {
location.href = data;
},
答案 1 :(得分:1)
您需要更改您的页面方法以实际返回某些内容,您当前通过void
返回类型返回任何内容,将其更改为:
[WebMethod(EnableSession = true)]
public static string OpenReport(string reportName)
{
Report report = reportsBll.GetReports().FirstOrDefault(x => reportQuestion != null && x.Id == reportQuestion.ReportId);
if (report != null)
{
return report.Url;
}
return String.Empty;
}
更新:Microsoft在ASP.NET AJAX 3.5中为JSON响应添加了一个父容器,以对抗潜在的跨站点脚本(XSS)攻击;因此你需要success
回调:
success: function (data) {
alert('success');
document.location.href = data.d;
}
中所述,有一些方法可以缓解这个问题