簡體   English   中英

使用ajax調用來調用C#[WebMethod]函數

[英]Call C# [WebMethod] function using an ajax call

我正在嘗試使用ajax調用從自定義模塊中的C#文件中調用函數。 我有一個.js文件,該文件使用ajax調用whitelist.aspx / isValidURL(我也嘗試過whitelist.cs作為文件擴展名和url,但沒有任何運氣)。 我需要訪問服務器方法isValidURL,傳入請求的URL,以查看請求的URL是否在有效URL列表中。 如果請求的URL在列表中,則我想對JavaScript文件返回true,否則返回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;

        }
    }
  1. 創建一個名為whitelist.aspx的新ASPX頁面,並將您的Web方法放入其中。
  2. stringify()您的參數,並使用POST而不是GET:

      $.ajax({ type: "POST", data: JSON.stringify({ requestedURL: transferurl }), ... 
  3. 返回值可以包裝,在這種情況下,您將按以下方式訪問它:

    .done(function (data) { if (data.d) { ... } })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM