簡體   English   中英

如何從服務器獲取JSON文件? (ASP.NET)

[英]How to get JSON file from server? (ASP.NET)

我有一個簡單的Web應用程序,使用JS使用一組單詞進行操作。 為了測試主要代碼,我只是將所需的數據放在腳本的變量中。

CONST WORDS = [
    ["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
    ["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
    ["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]

現在,我需要建立一個數據庫(已經完成)並從服務器獲取此類數據。 因此,問題是如何使用JS從服務器獲取JSON文件? 我知道如何發出GET請求,但是我應該在服務器上做什么以使其響應? (或者考慮到我已經從數據庫獲得了數據並且可以輕松地顯示在網頁上,也許有一種更簡單的方法可以在JS中獲取此數據)。 這是一個后端代碼

namespace LFrench
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
        }
    }
}

您需要在服務器端使用json返回類型方法。 比從get方法調用它,然后在服務器端執行方法,並填充List並通過轉換JSON格式返回該列表。

您需要了解的是您的請求流程。 如果您嚴格希望在Page_Loag事件中執行此操作,那么我想您將必須在Javascript中創建一個方法,該方法實際上將接受您的數據作為參數,然后從C# CodeBehind調用Javascript方法。 JSON格式。 此方法有效,但效率不高。

另一種方法是,在您的JQuery端,您應該在CodeBehind中對您的WebMethod進行ajax調用,該調用實際上將以JSON格式發送響應。 這是更干凈的方法。

您的JQuery應該如下所示:

$(document).ready(function(){
    $.ajax({
       method: "GET", accept: "application/json; charset=utf-8;",
       url: 'MyPage.aspx/GetDataFromDB', success: function(data){
            console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
       }, fail: function(err){
          console.log(err);
      }
    });
});

而且您的CodeBehind應該看起來像:

[WebMethod]
public static string GetDataFromDB()
{
    var myData = YourDbCall(); // Some method to retrieve data from database
    var body = new 
    {
        Firstname = myData.Firstname,
        Lastname = myData.Lastname,
        Email = myData.Email,
        // Any Other Information
    };
    var json = JsonConvert.SerializeObject(body);
    return json;

}

編輯以下是將您的Word Set作為JSON發送回的方式:

[WebMethod]
public static string GetDataFromDB()
{
    List<Words> WordsSet = Words.GetWords("Business");

    return JsonConvert.SerializeObject(WordsSet);

}

確保已從Nuget Package Manager Console安裝了Newtonsoft.JSON 如果不是,則可以打開Package Manager控制台並運行以下命令:

PM> Install-Package Newtonsoft.Json

暫無
暫無

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

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