2010-04-21 20 views
1

我正在爲有基金驅動的慈善機構做一些工作。每當有人做出承諾時,他們的承諾金額就會記錄到SQL Server中。他們希望在其他幾個網站上發佈許諾,所以我認爲,「哈哈!這是學習Web服務的好時機!」我假設我可以設置一個將服務承諾總額作爲字符串返回的Web服務,然後在調用Web服務的外部網站上轉儲一些jQuery代碼。大約9個小時後,我仍然試圖找出這些東西。這聽起來像JSONP是做跨域請求的唯一方法,但即使在回顧了一堆教程之後,我不知道如何讓我的.NET頁面返回正確的值,現在我想知道是否沒有這完全是一個更好的方式。任何人都可以提供完全簡化的代碼示例?使用jQuery從其他域檢索單個值

TL; DR:我需要從另一個web服務器使用jquery或javascript將一個值返回給一堆頁面。

回答

0

JSONP是要走的路。底線是您提供一個函數名稱用作查詢字符串中的回調函數,將返回的數據序列化爲JSON,然後將序列化數據(字符串)包裝在函數調用中。 jQuery將在腳本標記內接收到這個消息,以便它將使用JSON數據調用回調函數。

下面是從我的一個ASP.NET MVC項目改編的代碼。給定一個序列化對象和回調參數,它將返回一個可以作爲內容發回的字符串。在我的類中它實際上返回一個ContentResult,但我已經改變它返回一個簡單的字符串。

public class JsonPSerializer 
{ 
    private string Callback { get; set; } 

    public JsonPSerializer(string callback) 
    { 
     this.Callback = callback; 
    } 

    private static string GetJson<T>(T obj) 
    { 
     using (MemoryStream stream = new MemoryStream()) 
     { 
      var serializer = new DataContractJsonSerializer(typeof(T)); 
      serializer.WriteObject(stream, obj); 

      return Encoding.UTF8.GetString(stream.GetBuffer().TakeWhile(b => b != '\0')).ToArray()); 
     } 
    } 

    public string Serialize<T>(List<T> list) where T : IModel 
    { 

     StringBuilder builder = new StringBuilder(); 
     builder.AppendFormat("{0}([", Callback); 
     foreach (var obj in list) 
     { 
      builder.Append(GetJson(obj)); 
      builder.Append(","); 
     } 
     return builder.ToString().TrimEnd(',') + "])"; 
    } 

    public string Serialize<T>(T obj) where T : IModel 
    { 
     string content = GetJson(obj); 
     return Callback + "(" + content + ")"; 
    } 
} 
0

這是你的 「完全簡化了代碼示例」:

你的WebMethod(將其放置在文件後面example.aspx代碼):

[WebMethod(CacheDuration = 0, EnableSession = true)] 
public static YourResultType YourMethodName(string param1,int param2) 
{ 
    YourResultType result=new YourResultType(); 
    result.x1=true; 
    result.x2="The Response can be in any type"; 
return result; 
} 

你的結果類型:

public class YourResultType 
{ 
    public YourResultType(){} 
    public bool x1; 
    public string x2; 
} 

JavaScript代碼(基於jQuery):

$.ajax({ 
    type: "POST", cache: false, 
    url: "example.aspx/YourMethodName", 
    data: "{'randomparam':'" + ((new Date()).getTime()) + 
    //randomparam is for preventing cache 
    "','param1':'param1Value','param2':'param2Value'}", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(msg) { 
     if (msg.hasOwnProperty("d")) msg = msg.d; 
     //And Here, The msg parameter, 
     //contains the result of the WebMethod 
     //and you can use that like this: 
     alert(msg.x1);  
     alert(msg.x2); 
    } 
});