2012-04-29 81 views
0

我有一個函數用於從我的RESTFUL WCF服務中檢索數據。返回的數據必須是JSON。

在客戶機端

我有一個JavaScript功能稱爲自動提示象下面這樣:

function autosuggest(location){ 

var uri= 'http://localhost:2043/Suggest.svc/GetAirportsjson?location='+location; 
$.ajax({ 
     url:uri, 
     dataType: 'jsonp', 
     jsonp: 'callback', 
     jsonpCallback: 'jsonpCallback(e)', 
     success: function(e){ 
      alert("success"); 
     } 
    }); }; 

服務的接口:

[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetAirportsXML?location={location}")] 
    [OperationContract] 
    List<Suggestions> GetAirportDataXml(string location); 

    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetAirportsJSON?location={location}")] 
    [OperationContract] 
    List<Suggestions> GetAirportDataJson(string location); 

而在螢火蟲觀察位置的響應= m是

[{"AirportCode":"MMZ","AirportName":"Maimana","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"MZR","AirportName":"Mazar-i-sharif","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"IMZ","AirportName":"Nimroz","AreaCode":"701","CountryCode":"AF","CountryName":"Afghanistan"},{"AirportCode":"TMR","AirportName":"Aguemar","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"BMW","AirportName":"Bordj Badji Mokhtar","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"IAM","AirportName":"In Amenas","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MUW","AirportName":"Mascara-Ghriss","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MZW","AirportName":"Mechria","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"MQV","AirportName":"Mostaganem","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"HME","AirportName":"Oued Irara Apt","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"TMX","AirportName":"Timimoun","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"},{"AirportCode":"TLM","AirportName":"Zenata","AreaCode":"500","CountryCode":"DZ","CountryName":"Algeria"}] 

而且我還會提供我的服務代碼是

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using System.ServiceModel.Activation; 

namespace AutosuggestAPI.svc 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. 
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class Suggest : IService1 
    { 
     public string GetDateTime() 
     { 
      return DateTime.Now.ToString(); 
     } 


     private static List<Suggestions> GetDistinct(List<Suggestions> suggestions) 
     { 
      var length = suggestions.Count; 
      var Arr = new Suggestions[length]; 
      suggestions.CopyTo(Arr); 

      var dist = new HashSet<string>(); 

      foreach (var suggestion in Arr) 
      { 
       if (!dist.Contains(suggestion.AirportCode.ToString())) 
        dist.Add(suggestion.AirportCode.ToString()); 
       else 
       { 
        suggestions.Remove(suggestion); 
       } 
      } 
      return suggestions; 
     } 

     public List<Suggestions> GetAirportDataXml(string location) 
     { 
      var suggestions = new List<Suggestions>(); 
      var val = string.Empty; 
      for (int i = 0; i < 2; i++) 
      { 
       val = i == 0 ? "AirPortName" : "AirPortCode"; 
       SqlConnection conn = null; 
       try 
       { 
        // create and open a connection object 
        conn = new SqlConnection("Server=(local);DataBase=DBAirPortCodes;Integrated Security=SSPI"); 
        conn.Open(); 

        // 1. create a command object identifying 
        // the stored procedure 
        var cmd = new SqlCommand("sp_CheckCondition", conn) { CommandType = CommandType.StoredProcedure }; 

        // 2. set the command object so it knows 
        // to execute a stored procedure 

        // 3. add parameter to command, which 
        // will be passed to the stored procedure 
        cmd.Parameters.Add(new SqlParameter("@lookup", val)); 
        cmd.Parameters.Add(new SqlParameter("@searchfor", location)); 
        var reader = cmd.ExecuteReader(); 
        while (reader.Read()) 
        { 
         var suggestion = new Suggestions() 
         { 
          _airportCode = Convert.ToString(reader["AirPortCode"]).Trim(), 
          _airportName = Convert.ToString(reader["AirPortName"]).Trim(), 
          _areaCode = Convert.ToString(reader["AreaCode"]).Trim(), 
          _countryCode = Convert.ToString(reader["CountryCode"]).Trim(), 
          _countryName = Convert.ToString(reader["CountryName"]).Trim() 
         }; 
         suggestions.Add(suggestion); 
        } 
       } 
       finally 
       { 
        if (conn != null) 
         conn.Close(); 
       } 
      } 
      var distinctList = GetDistinct(suggestions); 
      return distinctList; 
     } 

     List<Suggestions> GetAirportDataJson(string location) 
     { 
      List<Suggestions> suggestions = GetAirportDataXml(location); 

      return suggestions; 
     } 


     public List<Suggestions> GetAirportDataJsonp(string location) 
     { 
      return GetAirportDataXml(location); 
     } 

     public List<Suggestions> GetAllSuggestions() 
     { 
      var suggestions = new List<Suggestions>(); 
      var val = string.Empty; 
      for (int i = 0; i < 2; i++) 
      { 
       val = i == 0 ? "AirPortName" : "AirPortCode"; 
       SqlConnection conn = null; 
       try 
       { 
        // create and open a connection object 
        conn = new SqlConnection("Server=(local);DataBase=DBAirPortCodes;Integrated Security=SSPI"); 
        conn.Open(); 

        var cmd = new SqlCommand("sp_GetAllAirports", conn) { CommandType = CommandType.StoredProcedure }; 

        var reader = cmd.ExecuteReader(); 
        while (reader.Read()) 
        { 
         var suggestion = new Suggestions() 
         { 
          _airportCode = Convert.ToString(reader["AirPortCode"]).Trim(), 
          _airportName = Convert.ToString(reader["AirPortName"]).Trim(), 
          _areaCode = Convert.ToString(reader["AreaCode"]).Trim(), 
          _countryCode = Convert.ToString(reader["CountryCode"]).Trim(), 
          _countryName = Convert.ToString(reader["CountryName"]).Trim() 
         }; 
         suggestions.Add(suggestion); 
        } 
       } 
       finally 
       { 
        if (conn != null) 
         conn.Close(); 
       } 
      } 
      var distinctList = GetDistinct(suggestions); 
      return distinctList; 
     } 

    } 
} 

問題是,調用是成功的,我得到了瀏覽器中的數據,但我無法在Jquery或Javascript中捕獲它。 有人可以幫忙嗎?

+0

嘗試增加的console.log(五)對你的成功的功能,看看您是否真正得到什麼,或者只是一個錯誤。我認爲當jsonp被預期時你會返回json。 – adeneo

+0

我希望它是json,但服務不在同一個域中。因此使用jsonp.Also成功功能根本沒有被擊中。在添加console.log後沒有任何記錄(e) –

+0

問題是返回的數據的可能性相當不錯。而要使用跨域jsonp,您正在使用的REST服務必須支持它,並返回有效的jsonp,而不是json,因爲這不起作用。您可以在服務器端執行此操作,因爲這很簡單,或者您可以使用Yahoo的YQL服務將數據轉換爲jsonp。但是,如果您有權訪問它,最好的選擇可能是讓REST服務支持jsonp。 – adeneo

回答

0

您正在將錯誤的字符串傳遞給jsonCallback。

應該

function autosuggest(location){ 

    var uri= 'http://localhost:2043/Suggest.svc/GetAirportsjson?location='+location; 
    $.ajax({ 
     url:uri, 
     dataType: 'jsonp', 
     jsonpCallback: 'jsonpCallback', 
     success: function(e){ 
      alert("success"); 
     } 
    }); 
}; 

也是爲什麼你用默認值覆蓋默認的回調參數的名字嗎?

編輯:似乎你並不真正瞭解jquery如何處理jsonp的東西。

jquery創建一個函數來處理jsonp請求的返回,它返回json作爲包裝到此函數調用中的純文本。你可以不提供功能可言,那就是最好的jQuery和更straitforward

看一看的following example

參數只有你需要提供是JSONP的數據類型

var r = $.ajax({ 
    url : uri 
    , dataType:'jsonp' 
    , success: function (e) { 
     viewModel.tweets(e.results);     
    }}); 

編輯2 :您的服務應處理「回調」參數,如果提供,包響應JSON在函數調用提供

請求:http://......../GetAirportsjson?location=....&callback=mycallback

響應:mycallback({ .... you real json response goes here .... })

除非你有這樣的你是不是做適當的JSONP響應

+0

我需要重寫默認回調,以便我可以訪問返回的數據並根據我的應用程序進行更改 –

+0

試過但無效。仍然無法獲取數據。並注意到jsonpCallback從不被調用。 –

+0

你在e – vittore