无法从Firefox和Chrome上的ajax函数和wcf rest服务获取数据,但在IE上工作正常

时间:2012-10-17 12:41:50

标签: jquery json ajax wcf google-chrome

我正在调用ajax函数,它从wcf rest服务返回JSON格式的一些数据。我在使用IE浏览器时收到数据,但在使用Mozilla和Chrome浏览器时无法获取数据。

以下是我正在使用的代码。

    <script src="js/JSon.js" type="text/javascript"></script>
    <script src="js/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="js/jquery.js" type="text/javascript"></script>

 function fillcategory() {
                var GetCategoryURl = "http://localhost:4444/Service1.svc/GetCategory"
                var drp = "";
                   $.ajax({
                        cache: false,
                        type: "GET",
                        async: false,  
                        url: GetCategoryURl,
                        dataType: "json",   
                        success: function (objCategory) {
                            Category = objCategory;                               
                        }
                    ,
                        error: function (xhr) {

                        }
                    });

                 fillSubcategory();
            }

Rquest Header是:

    OPTIONS /Service1.svc/GetCategory?_=1350649411289 HTTP/1.1
Host: localhost:4444
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.28) Gecko/20120306 Firefox/3.6.28
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://localhost:14853
Access-Control-Request-Method: GET
Access-Control-Request-Headers: x-requested-with

响应标题是:

    HTTP/1.1 405 Method Not Allowed
Allow: GET
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Fri, 19 Oct 2012 12:23:56 GMT

1 个答案:

答案 0 :(得分:0)

只需将它添加到您的global.asax文件中,以获取其确定的服务器端代码(服务),

 protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        EnableCrossDmainAjaxCall();

    }

    private void EnableCrossDmainAjaxCall()
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }