代码之家  ›  专栏  ›  技术社区  ›  Lars Holdgaard

从jQuery:GET调用.asmx Web服务是不允许的吗?

  •  1
  • Lars Holdgaard  · 技术社区  · 11 年前

    我有一个简单的页面。加载时,它调用一个web服务,然后我得到以下错误:

    an attempt was made to call the method using a GET request, which is not allowed
    

    我的JS代码:

        function getTutors() {
            var url = '<%= ResolveUrl("~/services/tutorservice.asmx/gettutors") %>';
            $.ajax({
                type: "GET",
                data: "{'data':'" + 'test-data' + "'}",
                url: url,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (d) {
                    alert('succes');
                    return d;
                },
                error: function () {
                    alert('fejl');
                }
            });
        }
    
        $(document).ready(function () {
            var tutors = getTutors();
            var locations = [];
        }
    

    我的web服务:

        [ScriptService]
    public class tutorservice : System.Web.Services.WebService {
    
        public tutorservice () {
    
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
    
        [WebMethod]
        public List<Tutor> gettutors(string data)
        {
            var tutorManager = new TutorManager();
            return tutorManager.GetTutorApplicants();
        }
    
    }
    

    我已经尝试删除contentTypes,即使没有数据变量,它仍然会给出相同的错误。

    我的最佳猜测是应该删除一些contentType/dataType,但我也尝试过。

    你知道我为什么会犯这个错误吗?

    1 回复  |  直到 11 年前
        1
  •  5
  •   zigdawgydawg    11 年前

    我可以想到两种选择:

    1) 在AJAX调用中使用POST而不是GET:

    type: "POST",
    

    或2)如果您必须使用GET,请将您的web服务方法配置为允许GETS:

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public List<Tutor> gettutors(string data)
    {
        var tutorManager = new TutorManager();
        return tutorManager.GetTutorApplicants();
    }
    

    并通过web.config允许GETS:

    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>