我正在尝试使用ajax调用从我的自定义模块中的C#文件调用函数。我有一个.js文件,它使用ajax调用whitelist.aspx / isValidURL(我也尝试过whitelist.cs作为文件扩展名和url而没有任何运气)。我需要访问服务器方法isValidURL,传入请求的URL,以查看请求的URL是否在有效URL列表中。如果请求的URL在列表中,那么我想返回true到javascript文件,否则返回false。这甚至可能吗?以下是我所拥有的代码:
Javascript代码:
$(document).ready(function () {
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
if (getUrlVars()["url"].indexOf("http") > -1) {
var urlArray = getUrlVars()["url"].split('/');
//var protocol = urlArray[0];
var transferurl = urlArray[2];
} else {
var transferurl = getUrlVars()["url"];
}
$.ajax({
type: "GET",
url: "whitelist.aspx/isValidURL",
data: {url:transferurl},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
if (data) {
//Redirect to the requested url because it was a valid url in the whitelist
setTimeout(function () { window.location.assign(transferurl); }, 5000);
} else {
//Don't redirect to the requested url because it wasn't a valid url in the whitelist
}
}).fail(function () {
//Don't redirect to the requested url because there was an error looking it up in the whitelist
});
});
C#代码:
public class whitelist
{
[WebMethod]
public static bool isValidURL(string requestedURL)
{
//Create a list of strings to contain all the "valid" URLs
var whiteList = new List<string>();
//Add URLs to the list
whiteList.Add("www.google.com");
foreach (string validURL in whiteList)
{
if (requestedURL == validURL)
{
return true;
}
}
return false;
}
}
答案 0 :(得分:0)
stringify()
您的参数并使用POST代替GET:
$.ajax({
type: "POST",
data: JSON.stringify({ requestedURL: transferurl }),
...
可以包装返回值,在这种情况下,您将按如下方式访问它:
.done(function (data) {
if (data.d) {
...
}
})