【问题标题】:call web service through jquery ajax通过 jquery ajax 调用 web 服务
【发布时间】:2014-01-15 13:33:53
【问题描述】:

我只想通过 jquery ajax 调用 web 服务.. 我做了一个 web 服务方法,它向我们展示了系统的当前日期时间.. 但是我的程序无法正常工作可能是我放的时候出现了一些错误Web服务的网址..如果您检查我的代码,将不胜感激..我只是希望最好的

这里是我的 Jquery 代码:

$(document).ready(function()

  {

       $("#btn").click(function() 
         {
            $.ajax(
            {
              type:"POST",
              url:"Service.asmx/CurrentTime",
              data:"{}",
              contentType:"application/json; charset=utf-8",
              dataType:"json",
              success: function(msg)
                 {
                   $("#show").text(msg.d);
                 }

                      });

                      });

                        });

我的网络服务代码:

       using System;

       using System.Collections.Generic;

       using System.Linq;

       using System.Web;

       using System.Web.Services;

       namespace WebService1

          {

              [WebService(Namespace = "http://microsoft.com/webservices/")]

              [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

              [System.ComponentModel.ToolboxItem(false)]

              [System.Web.Script.Services.ScriptService]

              public class Service1 : System.Web.Services.WebService
                 {


                     [WebMethod]
                     public string CurrentTime()
                            {
                                return DateTime.Now.ToString();
                             }
                     }
                     }

我还是没有解决这个问题...??????????

【问题讨论】:

  • data:"{}", 尝试删除它或使用这种方式:data:{},
  • 你遇到什么样的错误?
  • 我没有收到任何错误..这就是为什么我很困惑...我没有在数据中传递任何参数
  • @user3193071 你没有包含error: function(){} 回调。使用它来获取错误。
  • 这里的任何人都给我最好的解决方案..之后我完美地运行我的代码..????

标签: jquery ajax web-services


【解决方案1】:

试试这个:

$.ajax({
     type:"POST",
     url:"Service.asmx/CurrentTime",
     dataType : 'text',  //<------since your controller returns string use "text"
     success: function(msg){
         $("#show").text(msg);
     },
     error: function(xhr){  //<----use this callback to get the xhr errors
        console.log(xhr);
     }
});

注意:

由于您的控制器返回类型不是json,因此不要使用dataType : json and contentType,而是可以按照答案中的建议将dataType 用作text。此外,在您的成功函数中,您可以按照建议将数据放入所需的元素中。

【讨论】:

  • 我在数据类型中使用了 'text' 而不是 'json' 但仍然无法正常工作
  • 嘿,我使用了你的整个代码,但是兄弟.. 但实际上它仍然没有工作它没有显示任何错误
  • 你能在 chrome 检查器中调试吗?如果您的浏览器是 chrome,请检查网络选项卡,看看您的网络服务是否在那里被调用。
  • [System.Web.Script.Services.ScriptService]
  • 那是我的错误,现在应该是这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多