使用 XmlHttpRequest 和纯 JavaScript 调用 WebMethods

发布于 2024-09-07 04:36:19 字数 4921 浏览 1 评论 0原文

我的任务应该是相对简单的,但坦率地说,这让我感到困惑。我已经研究了它直到我的大脑被烧坏了,现在我正在下注,并向你们寻求帮助。

场景如下:

  • 我有一个用 WebService 装饰的 ASPX 页面 (Q2.aspx), WebServiceBindingScriptService 属性。
  • 该页面包含一个方法 GetAllContacts,该方法使用 WebMethod 进行修饰 属性并返回包含 JSON 数据的字符串。 (就其价值而言,该页面 它本身不包含其他控件或功能。)
  • 我有一个 HTML 页面,其中包含使用 XmlHttpRequest 的 JavaScript 对象来调用 ASPX 页面上的 GetAllContacts WebMethod 并进行转换 将 JSON 数据转换为 HTML 表。
  • 我已验证我的 Web.Config 文件包含适当的协议处理程序 对于 System.Web.webServices 下的 WebServices 部分中的 HttpGetHttpPut
  • 我已经验证我的 Web.Config 文件包含 ScriptModule 条目 System.webServer.modules 部分,并且它与相应的文档匹配。

但是,当我在浏览器中查看 HTML 页面时,会发生以下情况:

  • Web 请求已通过,但结果是来自 ASPX 页面的未处理的 HTML。
  • GetAllContacts 方法永远不会被调用,在其代码中设置断点即可证明这一点。
  • 然而,调用 Web 服务的代码被调用,并且 JavaScript 回调 请求完成时调用的函数被正确调用。

看来 JavaScript 代码大部分设置正确,但由于某种原因,我现在完全无法理解,HTML 页面将根本不执行 ASPX 页面上的 WebMethod ,而只是返回页面就好像它是一个纯 HTML GET 请求。显然,HTML 文档无法通过 JavaScript 的 eval 函数进行评估,这让我遇到了问题。 (另请注意,JSON 数据不会出现在返回的 HTML 中。)

坦率地说,我很困惑。我查看了数十篇 Microsoft 文章、StackOverflow 帖子、CodeProject 文章,谁知道还有什么。我的代码看起来没问题。但我更清楚。我错过了一些简单、愚蠢和明显的东西。我只需要有人向我指出这一点。

下面您将找到 ASPX 页面代码和 HTML 代码,希望它们能提供一些帮助。

ASPX 代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
    <body>
        <form runat="server" id="frmMain"/>
    </body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Satuit
{
    [WebService(Namespace="http://tempuri.org")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ScriptService]
    public partial class Q2 : Page
    {

        [WebMethod]
        public static string GetAllContacts()
        {
            return LoadJsonData();
        }

        private static string LoadJsonData()
        {
            using (var stringWriter = new StringWriter())
            {

                string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
                string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");

                using (var xmlTextReader = new XmlTextReader(xmlUri))
                {
                    var xpathDocument = new XPathDocument(xmlTextReader);
                    var xslTransform = new XslCompiledTransform();

                    xslTransform.Load(xslUri);
                    xslTransform.Transform(xpathDocument, null, stringWriter);

                    return stringWriter.ToString();
                }
            }
        }
    }
}

HTML 代码

    var objectData; // Receives the objectified results of the JSON request.

    var xmlhttp;
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
    xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function () 
    {
        if (xmlhttp.readyState == 4) 
        {
            if (xmlhttp.status == 200)
            {
                var jsonResultBuffer = xmlhttp.responseText;
                objectData = eval(jsonResultBuffer);
                DisplayTable();
            }
        }
    };
    xmlhttp.send(null);

    function DisplayTable()
    {       
        var sHtml = "";     
        sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";           
        for(i = 0; i < objectData.length; i++)
        {
            sHtml += "<tr>";
            sHtml += "<td>" + objectData.ID;
            sHtml += "<td>" + objectData.firstName + "</td>";
            sHtml += "<td>" + objectData.lastName + "</td>";
            sHtml += "<td>" + objectData.address + "</td>"; 
            sHtml += "</tr>"
        }
        sHtml += "</table>"         
        document.getElementById("divTable").innerHTML = sHtml;
    }    
</script>

开发环境详细信息

  • Vista Ultimate SP 2
  • Visual Studio 2008
  • .NET Framework 3.5
  • 解决方案尚未部署,因此它在“本地 Web 服务器”中运行 由 Visual Studio 提供。 (让我想知道我是否应该只部署 IIS 请
  • 注意,包含 WebMethod 的 ASPX 页面和 HTML 页面位于 相同的解决方案。

I have what should be a relatively simple task that's frankly got me stumped. I've researched it until my brain is fried, and now I'm punting, and asking you guys for help.

Here's the scenario:

  • I have an ASPX page (Q2.aspx) that is decorated with the WebService,
    WebServiceBinding, and ScriptService attributes.
  • That page contains a method, GetAllContacts, that is decorated with the WebMethod
    attribute and returns a string containing JSON data. (For what it's worth, the page
    itself contains no other controls or functionality.)
  • I have an HTML page that contains JavaScript which uses the XmlHttpRequest
    object to invoke the GetAllContacts WebMethod on the ASPX page and transform
    the JSON data into an HTML table.
  • I have verified that my Web.Config file contains the appropriate protocol handlers
    for HttpGet and HttpPut in the WebServices section under System.Web.webServices.
  • I have verified that my Web.Config file contains the ScriptModule entry under the
    System.webServer.modules section, and that it matches the appropriate documentation.

However, when I view the HTML page in a browser, the following occur:

  • The web request goes through, but the results are for the unprocessed HTML from the ASPX page.
  • The GetAllContacts method is never invoked, as evidenced by setting a breakpoint in its code.
  • The code to invoke the Web service, however, is invoked, and the JavaScript callback
    function that is invoked upon request completion is properly invoked.

It appears that the JavaScript code is largely set up correctly, but for some reason that is completely escaping me at this point, the HTML page will simply not execute the WebMethod on the ASPX page, and simply returns the page as though it were a plain HTML GET request. Clearly, an HTML document can't be evaluated by JavaScript's eval function, which brings me to my problem. (Also note that the JSON data appears nowhere in the HTML that's returned.)

I am, frankly, baffled. I've looked at dozens of Microsoft articles, StackOverflow posts, CodeProject articles, and who knows what else. My code looks like it's okay. But I know better. I'm missing something simple, stupid, and obvious. I just need someone to point it out to me.

Below you'll find the ASPX page code and the HTML code, in the hope that they'll shed some light.

ASPX Code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Q2.aspx.cs" Inherits="Satuit.Q2" enablesessionstate="False" %>
<html>
    <body>
        <form runat="server" id="frmMain"/>
    </body>
</html>
-- Codebehind
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace Satuit
{
    [WebService(Namespace="http://tempuri.org")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ScriptService]
    public partial class Q2 : Page
    {

        [WebMethod]
        public static string GetAllContacts()
        {
            return LoadJsonData();
        }

        private static string LoadJsonData()
        {
            using (var stringWriter = new StringWriter())
            {

                string xmlUri = HttpContext.Current.Server.MapPath("\\XmlData\\Contacts.xml");
                string xslUri = HttpContext.Current.Server.MapPath("\\XmlData\\Q2.xsl");

                using (var xmlTextReader = new XmlTextReader(xmlUri))
                {
                    var xpathDocument = new XPathDocument(xmlTextReader);
                    var xslTransform = new XslCompiledTransform();

                    xslTransform.Load(xslUri);
                    xslTransform.Transform(xpathDocument, null, stringWriter);

                    return stringWriter.ToString();
                }
            }
        }
    }
}

HTML Code

    var objectData; // Receives the objectified results of the JSON request.

    var xmlhttp;
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    xmlhttp.open("GET", "/Q2.aspx/GetAllContacts", true);
    xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xmlhttp.onreadystatechange = function () 
    {
        if (xmlhttp.readyState == 4) 
        {
            if (xmlhttp.status == 200)
            {
                var jsonResultBuffer = xmlhttp.responseText;
                objectData = eval(jsonResultBuffer);
                DisplayTable();
            }
        }
    };
    xmlhttp.send(null);

    function DisplayTable()
    {       
        var sHtml = "";     
        sHtml = "<table><tr><th>ID</th><th>First</th><th>Last</th><th>Address</th></tr>";           
        for(i = 0; i < objectData.length; i++)
        {
            sHtml += "<tr>";
            sHtml += "<td>" + objectData.ID;
            sHtml += "<td>" + objectData.firstName + "</td>";
            sHtml += "<td>" + objectData.lastName + "</td>";
            sHtml += "<td>" + objectData.address + "</td>"; 
            sHtml += "</tr>"
        }
        sHtml += "</table>"         
        document.getElementById("divTable").innerHTML = sHtml;
    }    
</script>

Dev Environment Details

  • Vista Ultimate SP 2
  • Visual Studio 2008
  • .NET Framework 3.5
  • Solution has not yet been deployed, so it's running in the "local Web server"
    provided by Visual Studio. (Makes me wonder if I shouldn't just deploy IIS
    under Vista.)
  • Note that the ASPX page containing the WebMethod and the HTML page reside within
    the same solution.

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

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

发布评论

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

评论(2

迷鸟归林 2024-09-14 04:36:19

我认为我们需要使用 POST 请求调用 Web 方法
尝试更改这部分代码

xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    {
            var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
            objectData = jsonResultBuffer.d;
            DisplayTable();
    }
};

响应以 JSON 格式返回,其中“d”作为 xmlhttp.responseText 中的键

I think we need to call web method with POST request
try changing this part of code

xmlhttp.open("POST", "/Q2.aspx/GetAllContacts", true);
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.setRequestHeader("Accept", "application/json");
xmlhttp.onreadystatechange = function () 
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    {
            var jsonResultBuffer = JSON.parse(xmlhttp.responseText);
            objectData = jsonResultBuffer.d;
            DisplayTable();
    }
};

Response is returned in JSON format with "d" as the key in xmlhttp.responseText

很糊涂小朋友 2024-09-14 04:36:19

请使用 jquery 尝试以下操作来查看 Web 服务是否可访问。

$.ajax({
        type: "POST",
        url: "Q2.aspx/GetAllContacts",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
           alert("success");
        },
        error: function(response, aa) {
            alert("fail");
        }
    });

苏雷因

Pls try the following using jquery to see the web service is accessible or not.

$.ajax({
        type: "POST",
        url: "Q2.aspx/GetAllContacts",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
           alert("success");
        },
        error: function(response, aa) {
            alert("fail");
        }
    });

Thurein

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