如何使用 Javascript 从 C# 调用 Json API

发布于 2025-01-09 00:08:25 字数 2414 浏览 1 评论 0原文

我使用 ASP.NET 和 C# 制作了此 Web API 应用程序,

此 API 的输出响应是 Json 对象 可以在 java 脚本应用程序中使用 Ajax 调用此 API,

这是 C# 代码:

 public string Get()
        {

            string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
            string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
            string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
            SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
            string[] Result = new string[10];
            DataTable dataTable = new DataTable();

            adap.Fill(dataTable);

            int i = 0;

            foreach (DataRow dataR in dataTable.Rows)
            {
                string Val;
                Val = Convert.ToString(dataR["Raspberry_name"]);
                Result[i] = Val;
                i++;
            }

             Object[]  obj = {
        new { RasspiName = Result}
       
    };
         

            if (dataTable.Rows.Count > 0)
            {
                return  JsonConvert.SerializeObject(obj);
            }

            return  "No Data Found";
            

        }


    }

输出是此 Json 对象:

[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]

JavaScript 代码是:

function Ajax(){

    var request = new XMLHttpRequest();

    
    request.onreadystatechange = function(){
      
      if(request.readyState == 4 && (request.status == 200)) {
        
        
       var DataR = [];
       
       DataR =JSON.parse(request.responseText) 
  
         console.log(DataR)
       
     }            

}

var url = 'http://localhost:41839/api/Musik';
  request.open('GET',url ,true);
  request.send()



}

我的问题是它把 Json 对象视为文本虽然我在 Java 脚本中使用了 ((JSON.parse)) 方法...例如,当我写 (( console.log(DataR[ 0 ])) 时,我只得到一个字母[ 而不是 Value 当我写 (( console.log(DataR[ 0 ].RasspiName)) 时,我得到 Undefined

我不知道问题是否来自 C# 代码或来自 Java 脚本

我希望你的帮助非常感谢

I made this Web API Apllication Using ASP.NET und C#

and output response from this API is Json object To can in java script Application Call this API with Ajax

this is C# Code :

 public string Get()
        {

            string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
            string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
            string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
            SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
            string[] Result = new string[10];
            DataTable dataTable = new DataTable();

            adap.Fill(dataTable);

            int i = 0;

            foreach (DataRow dataR in dataTable.Rows)
            {
                string Val;
                Val = Convert.ToString(dataR["Raspberry_name"]);
                Result[i] = Val;
                i++;
            }

             Object[]  obj = {
        new { RasspiName = Result}
       
    };
         

            if (dataTable.Rows.Count > 0)
            {
                return  JsonConvert.SerializeObject(obj);
            }

            return  "No Data Found";
            

        }


    }

and output is this Json Object:

[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]

JavaScript Code is:

function Ajax(){

    var request = new XMLHttpRequest();

    
    request.onreadystatechange = function(){
      
      if(request.readyState == 4 && (request.status == 200)) {
        
        
       var DataR = [];
       
       DataR =JSON.parse(request.responseText) 
  
         console.log(DataR)
       
     }            

}

var url = 'http://localhost:41839/api/Musik';
  request.open('GET',url ,true);
  request.send()



}

My problem is that it treats the Json object as text Although I used ((JSON.parse)) Method in Java Script ... For example when I write (( console.log(DataR[ 0 ])) I get only one Letter for Example [ Instead of Value when I write (( console.log(DataR[ 0 ].RasspiName)) I get Undefined

I dont know if proplem from C# code oder From Java Script

I hope your help thanks so much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坐在坟头思考人生 2025-01-16 00:08:25

我不明白你在后端代码示例中如何定义 API Get 方法,但我认为你应该这样设置:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
    //your code here
}

你可以使用 Ajax 发出 GET 请求:

function GetData() {
    try {
        $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "http://localhost:41839/api/Musik",
                data: '',
                dataType: "json",
                success: OnSuccessGetData,
                error: OnErrorGetData
         });
    }
    catch (ex) {
         console.log("GetData(): " + ex.toString());
    }
}

function OnSuccessGetData(result) {
    try {
        if (result.d !== "" && result.d !== null) {                   
            var dataSourceJson = JSON.parse(result.d);                   
        }
        else {
            console.log("OnSuccessGetData: result is null!");
        }
    }
    catch (ex) {
        console.log("OnSuccessGetData(): " + ex.toString());
    }
}
    
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
    try {
        console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
    }
    catch (ex) {
        console.log("OnErrorGetDashboardData(): " + ex.toString());
    }
}  

更多关于 JavaScript Get 请求 此处

I don't understand how you defined the API Get method in the back-end code example, but I think you should set something like this:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
    //your code here
}

You can use Ajax to make the GET request:

function GetData() {
    try {
        $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "http://localhost:41839/api/Musik",
                data: '',
                dataType: "json",
                success: OnSuccessGetData,
                error: OnErrorGetData
         });
    }
    catch (ex) {
         console.log("GetData(): " + ex.toString());
    }
}

function OnSuccessGetData(result) {
    try {
        if (result.d !== "" && result.d !== null) {                   
            var dataSourceJson = JSON.parse(result.d);                   
        }
        else {
            console.log("OnSuccessGetData: result is null!");
        }
    }
    catch (ex) {
        console.log("OnSuccessGetData(): " + ex.toString());
    }
}
    
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
    try {
        console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
    }
    catch (ex) {
        console.log("OnErrorGetDashboardData(): " + ex.toString());
    }
}  

More about JavaScript Get request here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文