如何在不刷新页面的情况下,从HTML页面[javascript]调用Web服务方法

11

我有一个Web服务,它将返回一个值。我的要求是,我需要从一个名为index.html的页面调用该Web服务,该页面上有一个HTML提交按钮。在点击按钮时,我会调用JavaScript函数,然后我想调用Web方法。我该如何实现。

我的Web服务地址是"localhost/ws/service.asmx",Web方法是HelloWorld

 <input type="button" value="Submit" id="btn_submit" onclick ="return fun()">

 function fun() {


    // here  I want to call the "helloworld" method.
    return true;
}
2个回答

16

您可以像这样使用jQuery从html页面执行POST或GET请求:

function fun() 
{
   var data="hello";
   $.get("http://localhost/ws/service.asmx/HelloWord", function(response) {
        data = response;
   }).error(function(){
  alert("Sorry could not proceed");
});

   return data;
}

或:

function fun() 
{
  var data="hello";
  $.post('http://localhost/ws/service.asmx/HelloWord',{},function(response) 
  {     data = response;
  }).error(function(){
  alert("Sorry could not proceed");
});

    return data;
}

警告(response),并检查返回到你的页面的内容。 - Aditya
[WebMethod] public string HelloWorld() { return "你好,世界"; }这是我的方法...一个简单的方法。 - ocp
尝试一下: 公共空白 HelloWord(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello world"); } - Aditya
请检查更新后的答案,如果请求中有错误。 - Aditya
抱歉,无法继续进行。 - ocp
显示剩余17条评论

7

您可以向Web服务发送Ajax请求。

 $.ajax({
            url: "WebServiceURL",
            data: "", //ur data to be sent to server
            contentType: "application/json; charset=utf-8", 
            type: "GET",
            success: function (data) {
               alert(data);
            },
            error: function (x, y, z) {
               alert(x.responseText +"  " +x.status);
            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接