2011-10-07 157 views
2

我有一個ASP.NET服務,我從一個返回JSON字符串的asxh文件訪問。除了從獨立服務器上的我們的博客子域訪問時,該服務工作得很好。 (blog.laptopmag.com)跨域使用jQuery訪問ashx服務

這裏是我的jQuery

$.ajax({ 
     type: "GET", 
     url: "http://www.laptopmag.com/scripts/service.ashx", 
     data: { "op": "get_products" }, 
     dataType: "json", 
     success: function (data) { 
      alert(data); 
     } 
    }); 

這裏是我的ashx文件

public class service : IHttpHandler { 
    public void ProcessRequest (HttpContext context) { 
     string jsonStr = "{}"; 
     string op = context.Request["op"]; 

     // Process request 

     context.Response.ContentType = "application/json"; 
     context.Response.Write(jsonStr); 
    } 

    public bool IsReusable { 
     get { 
      return false; 
     } 
    } 
} 

我試圖切換到JSONP請求,但必須做的事情錯誤,因爲我無法取回任何東西。這是我試過的。

,這裏是我的,似乎不工作從blog.laptopmag.com調用時

$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=ProcessRequest&op=get_products', function(json) { 
    console.log(json); 
    }); 

回答

1

OK可以找到,我想通了什麼問題與我的JSONP請求感謝以下職位: Jquery success function not firing using JSONP

問題在於請求沒有以預期的格式得到迴應。

現在,我的ashx的文件現在看起來是這樣的:

public void ProcessRequest (HttpContext context) { 
     string jsonStr = "{}"; 
     string op = context.Request["op"]; 
     string jsonp = context.Request["callback"]; 

     // Do something here 

     if (!String.IsNullOrEmpty(jsonp)) 
     { 
      jsonStr = jsonp + "(" + jsonStr + ")"; 
     } 

     context.Response.ContentType = "application/json"; 
     context.Response.Write(jsonStr); 
    } 

和jQuery的Ajax請求如下:

$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function(json) { 
    console.log(json); 
    }); 
0

安全限制,防止您跨域的jQuery AJAX調用,但也有變通方法JSONP嘗試。國際海事組織最簡單的方法是在您的網站上創建一個頁面,充當代理並使用您的jquery請求打開頁面。在代理的Page_Load中:

WebClient client = new WebClient(); 
Response.Write (client.DownloadString ("your-webservice-url")); 

其他解決方案可以通過quick Google search.

+0

這樣做幫助,或者你需要更多信息? – joelmdev

+0

我所得到的是一個頁面,其實際服務以HTML/Text格式顯示。我想我需要更多的幫助 – tomoguisuru