2013-05-15 127 views
1

我的问题与描述的here非常类似。使用jquery和jsonp的ASP.NET跨域web服务调用错误

然而,在我的情况下,我得到500内部服务器错误的萤火:

请求格式是无法识别的URL在“/ HelloWorld的”意外结束。

我的asp.net 4.0 web服务调用是跨域的,并从超过十几个其他网站的建议我相信我已经配置了一切,以便让这种情况发生正确,但显然我没有。我究竟做错了什么?

我正在使用JSONP而不是JSON。如果所有内容都在同一台服务器上,则Web服务按预期工作。我的问题是调用Web服务的HTML页面的主机提供程序不允许服务器端代码,否则我只是把所有内容放在一个地方并完成它!

下面

是我的代码/标记:

的web.config:

<?xml version="1.0"?> 
    <configuration> 
    <system.webServer> 
    <httpErrors errorMode="Detailed"></httpErrors> 
    <asp scriptErrorSentToBrowser="true"></asp> 
    <modules> 
     <add name="ContentTypeHttpModule" 
        type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule" /> 
    </modules> 
    </system.webServer> 
    <system.web> 
    <customErrors mode="Off"></customErrors> 
    <compilation debug="true" targetFramework="4.0"/> 
    <trust level="Full"/> 
    <pages clientIDMode="Static"/> 
    <webServices> 
     <protocols> 
     <add name="HttpGet"/> 
     <add name="HttpPost"/> 
     </protocols> 
    </webServices> 
    <!--<httpModules> 
     <add name="ContentTypeHttpModule" 
        type="ContentTypeHttpModule.ContentTypeHttpModule, ContentTypeHttpModule" /> 
    </httpModules>--> 
    </system.web> 
</configuration> 

HTML文件的javascript:

function test() { 
      $.ajax({ 
       url: 'http://designonlinelettering.com/RenderImage.asmx/HelloWorld', 
       data: {}, 
       contentType: "application/json; charset=utf-8", 
       dataType: "jsonp", 
       success: function (result) { 
        var data = result.d; 
        alert(data); 
       }, 
       error: function (e) { 
        alert('error: ' + e.d); 
       } 
      }); 
     } 

Web服务代码:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public string HelloWorld() 
{ 
return "Hello World"; 
} 

ContentTypeHttpModule代码是从这个非常翔实blog,从中我得到了我的大部分方向的拍摄。如前所述

感谢您的帮助......

+1

的contentType和错误选项JSONP请求,仅供参考 –

+1

你所得到的错误是服务器端的,无关的jQuery。直接导航到'http:// designonlinelettering.com/RenderImage.asmx/HelloWorld',你会看到。 –

回答

1

,如果你在浏览器中查看http://designonlinelettering.com/RenderImage.asmx/HelloWorld你会看到错误。添加一个?callback = x并没有帮助。它只会为正确设置了数据/响应类型的POST请求返回JSON。

ASMX有问题,并且不会为GET请求返回JSON ...您最好的选择是使用ASHX和Response.Render JSON(我推荐使用JSON.Net作为编码器)。不需要为$就

... 
using Newtonsoft.Json; 
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
... 
    var ret = JsonConvert.SerializeObject(
    objectToReturn 
    ,new IsoDateTimeConverter() 
    ,new DataTableConverter() 
    ,new DataSetConverter() 
); 
    //only need the datatable, and dataset converters if you're returning those types 

    //jsonp should have a callback on the querystring, in your jquery 
    // request append "pathto.ashx?callback=?" 
    context.Response.ContentType = "application/javascript"; 
    context.Response.Write(string.format(
    "{0}({1});" 
    ,context.Request.QueryString["callback"] 
    ,ret 
)); 
... 
+1

谢谢!这工作完美。 – RoastBeast