【问题标题】:Calling Web Method in Web Service在 Web 服务中调用 Web 方法
【发布时间】:2014-06-26 01:58:09
【问题描述】:

基本上,我正在尝试在 ASP.NET 的 JavaScript 类中使用 Web 服务方法。所以这是我的网络服务中的方法:

[WebMethod]
    public DataSet GetFireStation()
    {
        SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
        string select = "select * from dbo.FireStation ";
        sqlConnection1.Open();
        // Create an Adapter
        SqlDataAdapter da = new SqlDataAdapter(select, sqlConnection1);
        // Create a New DataSet
        DataSet ds = new DataSet();
        // Fill The DataSet With the Contents of the Stock Table
        da.Fill(ds, "FireStation");
        sqlConnection1.Close();
        // Now Return ds which is a DataSet
        return (ds);
    }

然后这是我的 HTML 代码,它调用 JavaScript 类中的函数:

 case "Accident":
            if (type == 'Accident') {
                symbol = new esri.symbol.PictureMarkerSymbol('img/Accident.gif', 25, 20);
                htmlStr = htmlStr + "<input type='button' id='btnHosPoint' class='infoTempButton infoTempOrange' title='To Hospital' value='' onclick='getSafetyCoordXY(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ", " + '\"' + type + '\"' + ");connectNearestRoute(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
                                    + "<input type='button' id='btnClinicPoint' class='infoTempButton infoTempOrange' title='To Clinic' value='Clinic' onclick='connectNearestClinic(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
                                    + "<input type='button' id='btnFirePoint' class='infoTempButton infoTempOrange' title='Nearest Fire Station' value='FS' onclick='ConnectNearsetFireStation(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />"
                                    + "<input type='button' id='btnPolicePoint' class='infoTempButton infoTempOrange' title='Nearest Police Station' value='Police' onclick='ConnectNearsetPolice(" + $(this).find("actualX").text() + ", " + $(this).find("actualY").text() + ");' />";
                var point = new esri.geometry.Point({ "x": $(this).find("actualX").text(), "y": $(this).find("actualY").text(), "spatialReference": { "wkid": 3414 } });
                var graphic = new esri.Graphic(point, symbol);
                map.graphics.add(graphic);

                var infoTemplate = new esri.InfoTemplate();
                infoTemplate.setTitle("<img src='img/Accident.gif' style='width:25px; height:25px;'/>&nbsp;&nbsp; " + type);
                infoTemplate.setContent("Information: " + incidentMessage + "</br>" + "</br>" + htmlStr);

                graphic.setSymbol(symbol);
                graphic.setInfoTemplate(infoTemplate);
                incidentLocation.push(graphic);
                htmlStr = "";
            }
            break;

这是我在 JavaScript 类中的函数,它从数据库中检索数据,该数据将通过 Web 服务方法传递:

编辑

function ConnectNearsetFireStation(x, y) {

    map.infoWindow.hide();
    //map.infoWindow.resize(350, 120);

    var Fire = [];
    var FireStationPointGraphic = [];

    $.ajax({
        'type'          : 'GET',
        'url'           : 'http://localhost/SgDataService.asmx' + 'GetFireStation',
    'success'       : function(results){
    $.each(GetFireStation(), function () {
        var name = $(this).find("ID").text();

        firestation = $(this).find("Name").text();
        address = $(this).find("Address").text();
        postal = $(this).find("PostalCode").text();
        coordX = $(this).find("X").text();
        coordY = $(this).find("Y").text();

        // Compute Distance
        var IncidentPoint = new esri.geometry.Point({ "x": x, "y": y, "spatialReference": { "wkid": 3414 } });
        var FireStationPoint = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
        var distance = esri.geometry.getLength(IncidentPoint, FireStationPoint);

        Fire.push(distance);

        var point = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
        var symbol = new esri.symbol.PictureMarkerSymbol('/SAFETY_AT_SG/Images/Features/FireStation.gif', 25, 25);
        var PointGraphic = new esri.Graphic(point, symbol);

        var infoTemplate = new esri.InfoTemplate();

        infoTemplate.setTitle("<img src='/SAFETY_AT_SG/Images/Features/PoliceStation.png' style='width:25px; height:25px;'/>&nbsp;&nbsp; " + firestation);
        infoTemplate.setContent("<b>FireStation: </b>" + firestation + "<br/>"
                + "<b>Address: </b>" + address + "<br/>"
                + "<b>PostalCode: </b>" + postal + "<br/>"
                );
        PointGraphic.setSymbol(symbol);
        PointGraphic.setInfoTemplate(infoTemplate);

        //Store PoliceStation To Array
        FireStationPointGraphic.push(PointGraphic);

        //OneMap.map.graphics.add(PointGraphic)
    }
    );
    }
    });

    var minDist = Math.min.apply(null, Fire); //Get Smallest Distance

    for (var i = 0; i < Fire.length; i++) {
        if (minDist == Fire[i]) {
            var myX = FireStationPointGraphic[i].geometry.x;
            var myY = FireStationPointGraphic[i].geometry.y;

            OneMap.map.graphics.add(FireStationPointGraphic[i]);
            RouteU(x + ',' + y + ";" + myX + ',' + myY);
            break;
        }
    }
}

但是,当我尝试在 conenctNearestFireStation() 中调用 GetFireStation() 时,它告诉我一条错误消息,即 GetFireStation 未定义。我想知道为什么会这样。如果我的 JavaScript 类正在调用其中的方法,我是否需要添加对 Web 服务的任何引用?

提前致谢。

【问题讨论】:

  • JavaScript 在客户端执行。您的 Web 方法在服务器上可用。您需要调用ajax 来执行 web 方法并将结果返回给客户端
  • 呃... JavaScript 没有类。你的“HTML 代码”看起来像 C#。什么?

标签: c# javascript asp.net web-services


【解决方案1】:

我认为代码最终应该是这样的

function ConnectNearsetFireStation (x, y){

    var Fire = [];
    var FireStationPointGraphic = [];

    var setRoute = function (){
        var minDist = Math.min.apply(null, Fire); //Get Smallest Distance

        for (var i = 0; i < Fire.length; i++) {
            if (minDist == Fire[i]) {
                var myX = FireStationPointGraphic[i].geometry.x;
                var myY = FireStationPointGraphic[i].geometry.y;

                OneMap.map.graphics.add(FireStationPointGraphic[i]);
                RouteU(x + ',' + y + ";" + myX + ',' + myY);
                break;
            }
        }
    }

    var processFireStations = function (allFireStations){
        $.each(allFireStations, function (){
            var name = $(this).find("ID").text();

            firestation = $(this).find("Name").text();
            address = $(this).find("Address").text();
            postal = $(this).find("PostalCode").text();
            coordX = $(this).find("X").text();
            coordY = $(this).find("Y").text();

            // Compute Distance
            var IncidentPoint = new esri.geometry.Point({ "x": x, "y": y, "spatialReference": { "wkid": 3414 } });
            var FireStationPoint = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
            var distance = esri.geometry.getLength(IncidentPoint, FireStationPoint);

            Fire.push(distance);

            var point = new esri.geometry.Point({ "x": coordX, "y": coordY, "spatialReference": { "wkid": 3414 } });
            var symbol = new esri.symbol.PictureMarkerSymbol('/SAFETY_AT_SG/Images/Features/FireStation.gif', 25, 25);
            var PointGraphic = new esri.Graphic(point, symbol);

            var infoTemplate = new esri.InfoTemplate();

            infoTemplate.setTitle("<img src='/SAFETY_AT_SG/Images/Features/PoliceStation.png' style='width:25px; height:25px;'/>&nbsp;&nbsp; " + firestation);
            infoTemplate.setContent("<b>FireStation: </b>" + firestation + "<br/>"
                    + "<b>Address: </b>" + address + "<br/>"
                    + "<b>PostalCode: </b>" + postal + "<br/>"
                    );
            PointGraphic.setSymbol(symbol);
            PointGraphic.setInfoTemplate(infoTemplate);

            //Store PoliceStation To Array
            FireStationPointGraphic.push(PointGraphic);

            //OneMap.map.graphics.add(PointGraphic)
        });

        // Once the $.Each is over, map the route
        setRoute();
    };

    var getFireStations = function (){
        $.ajax({
            'type'          : 'GET',
            'url'           : 'http://localhost/SgDataService.asmx' + 'GetFireStation',
            'success'       : processFireStations
        });
    };



    map.infoWindow.hide();
    //map.infoWindow.resize(350, 120);

    getFireStations();      // start everything
}

【讨论】:

  • 它向我抛出了一条错误消息:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost:2752'。
  • 这意味着您的 html 页面和您的 web 服务不在同一个域中托管。你需要自己解决这个问题
  • 好的,当然。非常感谢!
【解决方案2】:

JavaScript 在客户端执行。您的 Web 方法在服务器上可用。您需要进行 ajax 调用来执行 web 方法并将结果返回给客户端

这意味着您需要编写一个额外的 javascript 函数。 JQuery 将真正为您提供帮助,因为它提供了一些简化的、跨浏览器兼容的方法来进行 ajax 调用。

// $ is a shortcut for jQuery
$.ajax({
    'type'          : 'GET',
    'url'           : yoururl + 'GetFireStation'
    'success'       : function(results){
                          // do stuff
                      }
}});

请注意:

AJAX 进行异步调用,这意味着您可能必须 重新思考到目前为止您是如何编写 javascript 函数的

更新

更多关于 jQuery 的信息和示例API page for ajax

【讨论】:

  • 我应该为 yoururl 替换什么?我当前的网址是localhost:2752/index.aspx。所以我只是简单地替换它?
  • @20Cents 是的,应该是你的GetFireStationwebservice 的url
  • @20Cents 查看ajax calls的jQuery文档
  • 你能帮我检查一下编辑过的部分吗?我不确定我是否以正确的方式做事
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
相关资源
最近更新 更多