javascript - 调用网络服务 AngularJS

标签 javascript json angularjs html web-services

这是我的示例,单击按钮时我没有得到任何信息。

    <!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
    <script type="text/javascript" src="main.js" defer></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
</head>
<body ng-app="myAppModule">
    <div ng-controller="myAppController" style="text-align: center">

        <button ng-click="calculateQuantity()">Calculate</button>

    </div>

    <script>
        var myAppModule = angular.module('myAppModule', []);
        myAppModule.controller('myAppController', function ($scope, $http) {
            var CelsiusVal = "10";
            $scope.calculateQuantity = function () {
                alert("I'm here")
                $http.get('http://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit', { params: { Celsius: CelsiusVal } }).
                success(function (data) {alert("succ");})
                .error(function () { alert("error"); }); 
            };
        });
    </script>
</body>
</html>

我需要从网络服务获取结果。

注意更新了新的源示例!

最佳答案

首先,您的代码文件应该被调用:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js" defer></script>

其中 defer 告诉它应该在 dom 元素加载后加载。

第二,相反

$http.get('http://http://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit' ...

你应该有

$http.get('http://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit' ...

第三,改为

.success(function (data) {alert("succ");});
error(function () { alert("error"); });

你应该有

.success(function (data) {alert("succ");})
.error(function () { alert("error"); });

终于

由于浏览器内置的同源策略限制,您无法发送跨域 AJAX 请求。为了使其工作,包含 jQuery 代码的 HTML 页面必须托管在与 Web 服务相同的域 ( http://www.w3schools.com )。

有一些解决方法涉及在服务器上使用 JSONP,但由于您的 Web 服务是 SOAP,因此这是行不通的。

如果您无法将 javascript 移至与 Web 服务相同的域,那么唯一可靠的方法是构建一个服务器端脚本,该脚本将托管在与 javascript 代码相同的域上,并充当两个域之间的桥梁。因此,您可以向服务器端脚本发送 AJAX 请求,该脚本反过来将调用远程 Web 服务并返回结果。

如果他们启用了 GET 请求,您可以使用 CORS 代理来实现此目的。查询起来很简单

"https://crossorigin.me/http://www.w3schools.com/xml/tempconvert.asmx?op=CelsiusToFahrenheit&Celsius=" + CelsiusVal

但在这种情况下这是不可能的。

<小时/>

如何在 C# 中执行此操作的示例(假设它位于同一服务器中)

public static string GetFahrenheit(string celsius="20")
{
    const string url = "http://www.w3schools.com/xml/tempconvert.asmx";
    const string action = "http://www.w3schools.com/xml/CelsiusToFahrenheit";
    var soapEnvelopeXml = new XmlDocument();
    var soapString =
        $@"
        <soap:Envelope 
            xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' 
            xmlns:xsd='http://www.w3.org/2001/XMLSchema' 
            xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
            <soap:Body>
            <CelsiusToFahrenheit xmlns ='http://www.w3schools.com/xml/'>
                <Celsius> {celsius} </Celsius>
            </CelsiusToFahrenheit>
            </soap:Body>
        </soap:Envelope>";
    soapEnvelopeXml.LoadXml(soapString);
    var webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    using (var stream = webRequest.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }
    var asyncResult = webRequest.BeginGetResponse(null, null);
    asyncResult.AsyncWaitHandle.WaitOne();
    using (var webResponse = webRequest.EndGetResponse(asyncResult))
    using (var rd = new StreamReader(webResponse.GetResponseStream()))
    {
        var soapResult = rd.ReadToEnd();
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(soapResult);
        var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
        nsmgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
        nsmgr.AddNamespace("w3", "http://www.w3schools.com/xml/");
        nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
        nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        var result = xmlDoc.DocumentElement?.SelectSingleNode("/soap:Envelope/soap:Body/w3:CelsiusToFahrenheitResponse/w3:CelsiusToFahrenheitResult", nsmgr)?.InnerText;
        return result;
    }
}

之后您可以创建一个 Web 方法:

[WebMethod]
public static string GetFahrenheitFromW3(string celsius)
{
    return GetFahrenheit(celsius);
}

并从 javascript 调用它

$http.get('yourController.aspx/GetFahrenheitFromW3', { params: { Celsius: CelsiusVal } })
  .success(
    function (data) {
      alert("succ: "+data[0]);
    })
  .error(
    function () { 
      alert("error"); 
    }
  ); 

关于javascript - 调用网络服务 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33670309/

相关文章:

javascript - href 目标 rel 变化

html - 在 Angular 2 和 Typescript 的数组中定义数组

ANDROID 在 map View 中显示最近的 10 个位置

angularjs - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 Origin 'http://xxxxx.azurewebsites.net'

javascript - AngularJS 新手错误

javascript - 如何使用 javascript 禁用第一次鼠标单击网页上的操作?

javascript - 如何将两个数组缓冲区合并为一个?

javascript - jQuery:点击时显示,点击时隐藏,无限循环

Javascript - If 语句阻塞代码

angularjs - 如何在同一页面上呈现两个 angular.js View ?