简体   繁体   English

如何通过 AJAX (Native JS) 调用 ASP.NET WebMethod

[英]How to call an ASP.NET WebMethod via AJAX (Native JS)

Is there a way to call a WebMethod using native JS AJAX?有没有办法使用本机 JS AJAX 调用 WebMethod?

Similar to:相似:

           $.ajax({
                    type: "POST",
                    url: "AssignAdditional_Equip.aspx/getEquipListing",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var result = JSON.parse(data.d);
                        console.log(result);
                    },
                    error: function (response) {
                        alert(response);
                    }
                });  

The code below is my attempt:下面的代码是我的尝试:

var requestVar = new XMLHttpRequest();
requestVar.open('GET', 'AssignAdditional_Equip.aspx/getEquipListing');
requestVar.onload = function () {
    if (requestVar.status === 200) {
        console.log(requestVar.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
requestVar.send();

Edit: Here's my webmethod on codebehind to clear up some confusion编辑:这是我关于代码隐藏的 webmethod 以消除一些混乱

    <WebMethod>
Public Shared Function getEquipListing()
    Dim equipType_Options As New List(Of String)
    Dim serializer As New JavaScriptSerializer
    Dim sqlConn As New SqlConnection
    Dim reader As SqlDataReader

    sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ITSGinventory").ConnectionString

    Dim sqlCmd As New SqlCommand("SELECT DISTINCT(Equipment_Type) FROM tbl_Equipments ORDER BY Equipment_Type ASC", sqlConn)

    sqlConn.Open()

    reader = sqlCmd.ExecuteReader

    While reader.Read()
        equipType_Options.Add(reader("Equipment_Type"))
    End While

    sqlConn.Close()
    sqlConn.Dispose()

    Return serializer.Serialize(equipType_Options)
End Function

The webmethod is supposed to return a serialized list of strings. webmethod 应该返回一个序列化的字符串列表。 Using JQuery, it works as intended.使用 JQuery,它按预期工作。 But my native AJAX approach returns the HTML markup of the page instead of the string values.但是我的原生 AJAX 方法返回页面的 HTML 标记而不是字符串值。 Am I doing it wrong?我做错了吗?

I think you can use fetch function with json method to extract from http response.我认为您可以使用 fetch 函数和 json 方法从 http 响应中提取。 Well explained how to use here . 在这里很好地解释了如何使用。 For example:例如:

let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}

Okay, so after reading, researching and rewriting my code, I was able to make this work.好的,在阅读、研究和重写我的代码后,我能够完成这项工作。 I only needed to add xmlHttp.setRequestHeader('Content-Type', 'application/json');我只需要添加xmlHttp.setRequestHeader('Content-Type', 'application/json'); and was able to get a response from my WebMethod.并且能够从我的 WebMethod 获得响应。 LOL.哈哈。

Always keep this in mind when trying to call/invoke ASP.NET WebMethods that has a JSON return type.在尝试调用/调用具有 JSON 返回类型的 ASP.NET WebMethods 时,请始终牢记这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM