问题
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