0
我想從自定義模塊中的C#文件使用ajax調用調用函數。我有一個使用ajax調用whitelist.aspx/isValidURL的.js文件(我也試過whitelist.cs作爲文件擴展名和url,沒有任何運氣)。我需要訪問服務器方法isValidURL,傳入請求的URL,以查看請求的URL是否在有效URL列表中。如果請求的url在列表中,那麼我想返回true到JavaScript文件,否則返回false。這甚至有可能嗎?下面是我thusfar代碼:使用Ajax調用調用C#[WebMethod]函數
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;
}
}
非常感謝您的回覆如此之快,但我仍然收到404(Not Fount)錯誤。我的ajax方法尋找的網址如下所示:http:// localhost:5551/whitelist.aspx/isValidURL我也嘗試過url:http:// localhost:5551/whitelist.aspx,但那也不起作用。我錯過了什麼嗎?我是否需要一個控制器和路由器來給我的.aspx頁面一個url或者什麼?感謝您的幫助。 – EmeraldArcher 2014-09-02 20:26:30
@EmeraldArcher如果您使用的是MVC,那麼您可以使用控制器操作而不是webmethod。我不是很流利的MVC,所以如果這是你的場景,谷歌搜索應該找到你很多的例子。:) – 2014-09-02 20:31:30
謝謝Slippery皮特我會嘗試。 – EmeraldArcher 2014-09-02 20:33:33