Call external site webmethod using jsonp?

白昼怎懂夜的黑 提交于 2019-12-06 13:01:00

问题


I'm trying to call external site webmethod, and post some data. I tried a lot of different ways and still cannot get the method to be called.

Here is my js code:

$.ajax({
            url: "http://sitename.com/methods.aspx/mywebmethod",
            data: "{'id':'" + 4 + "'}",
            dataType: "jsonp",
            type: "GET",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

Here is my webmethod code:

[WebMethod()]
        public static bool mywebmethod(int id)
        {
if(id != 0){
            return true;}
else{return false;}
        }

and I always get the same response

Error: jQuery{code} was not called

What I'm missing?


回答1:


JSONP is not magic.

You can only use JSONP to read data from a URL that returns JSONP script.
ASP.Net WebMethods do not support JSONP.




回答2:


I guess you're missing the proper attributes, as following (in an .asmx definition):

    [WebMethod(EnableSession = true)] // optional, but usually forgotten
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public bool MyMethod(int id)
    {
        return true;
    }

plus, you need to have Content-rewrite module for handling the leading callback parameter as well:

http://www.codeproject.com/Articles/43038/Accessing-Remote-ASP-NET-Web-Services-Using-JSONP



来源:https://stackoverflow.com/questions/9997310/call-external-site-webmethod-using-jsonp

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