Calling .asmx webservice from jQuery: GET is not allowed?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 18:09:59

问题


I have a simple page. On load, it calls a web service, and then I get the following error:

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

My JS-code:

    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 = [];
    }

My web service:

    [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();
    }

}

I have tried to remove the contentTypes, and even without the data variable, it still gives the same error.

My best guess is some contentType / dataType should be removed, but I have tried that as well.

Any ideas about why I get this error?


回答1:


I can think of two options:

1) Use a POST instead of a GET in your AJAX call:

type: "POST",

or 2) If you must use a GET, configure your web service method to allow GETS:

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

and allow GETS via web.config:

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


来源:https://stackoverflow.com/questions/18703838/calling-asmx-webservice-from-jquery-get-is-not-allowed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!