如何使用ajax从普通html调用远程服务器上托管的.asmx Web服务

时间:2014-11-19 11:20:04

标签: html asp.net ajax web-services asmx

我使用asp.net创建了一个简单的Web服务,并托管在我的机器的IIS服务器上。我试图从普通的html页面调用此Web服务,而不使用Asp.net。问题是我没有得到回应。以下是我的代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Calling Classic Web Services with jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("a#SayHello").click(function (e) {
          e.preventDefault();

          $.ajax({
            type: 'POST',
            data: '{firstName:10,lastName:15}',
          //  url: 'Service.asmx/SayHello',
            url: 'http://192.168.1.20/MyService/Service.asmx/SayHello',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',

            success: function(response) {

                alert(response.d); //getting the Response from JSON

            },
            failure: function(msg) {
                alert(msg);
            }
          });
        });
      });    
    </script>
</head>
<body>
  <input id="name" /><a id="SayHello" href="#">Greetings!</a>  
</body>
</html>

任何人都可以帮我解决我在这段代码中出错的地方.. ??如果我在ASP.Net环境中运行它,它可以很好地工作。但是,如果我主持这个,那么它不起作用。请帮帮我...... !!

2 个答案:

答案 0 :(得分:0)

您确定Web服务是以JSON格式响应吗?它通常以XML格式回答。此外,<script>广告块应该放在<body>而不是<head>

答案 1 :(得分:0)

如果您在同一个IIS上托管了Web服务,则将192.168.1.20更改为localhost,然后尝试..