2011-03-03 54 views
1

我已經jQuery的使用AJAX/JSON抓住一個元素ID一個WebMethod可以使用,然後點擊:返回多個值jQuery中從

[System.Web.Services.WebMethod] 
public static string EditPage(string nodeID) 
{ 
    DataTable dt = new DataTable(); 
    using (SqlConnection con = new SqlConnection(Global.conString)) 
    using (SqlCommand cmd = new SqlCommand("contentPageGetDetail", con)) 
    { 
     cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value = Global.SafeSqlLiteral(nodeID, 1); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.ExecuteNonQuery(); 
     using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
     { 
      da.Fill(dt); 
     } 
    } 
    if (dt.Count > 0) 
    { 
     string pageTitle = dt.Rows[0]["Title"].toString(); 
     string contentID = dt.Rows[0]["ContentID"].toString(); 
     return pageTitle, contentID, nodeID; 
    } 
    else 
    { 
     return "Failed"; 
    } 
} 

當它的時間來恢復我想抓住所有的內容從返回存儲過程返回成功部分的jquery方法,並在文本字段中設置隱藏字段,下拉值和標題。

在jQuery中,我嘗試使用「pageTitle」,但它未定義。在顯示錶單之前,我需要做什麼來完成jQuery的工作以獲取返回的內容並填充Web窗體中的字段?

+0

這是無效的語法。 – SLaks 2011-03-03 19:12:38

+0

那是什麼呢? 'return pageTitle,contentID,nodeID;'? – hunter 2011-03-03 19:13:00

+0

我需要返回的示例。我不知道返回多個字符串的正確方法。 – balexander 2011-03-03 19:13:52

回答

1

如果你想使用你從jQuery的嘗試返回字符串:

success: function(msg) { 
    alert(msg.d); 
} 

msg.d將保存您從web服務調用返回的字符串。如果你想返回多個字符串,試着在它們之間添加一個預定義的字符串,並將它們分割到你的jquery成功函數中。像:

yourfirststring||@@||yoursecondstring||@@||yourthirdstring 

var strings = msg.d.split("||@@||"); 
11

你需要創建一個結構或類返回:

public struct TheStruct 
{ 
    public string pageTitle; 
    public int contentID, 
    public int nodeID; 
} 

[System.Web.Services.WebMethod] 
public static TheStruct EditPage(string nodeID) 
{ 
    <your code here> 

    var result = new TheStruct(); 
    result.pageTitle = "Test"; 
    result.contentID = 1; 
    return result; 
} 

如果傳遞:

contentType: "application/json; charset=utf-8", 
在AJAX調用

,你會得到一個JSON回覆,你可以解析,如:

var obj = jQuery.parseJSON(webserviceReply); 
alert(obj.pageTitle); 
+0

認爲你可以添加更多?我不知道作爲RETURN變量放置什麼,我總是收到錯誤。 – balexander 2011-03-04 03:55:12

+0

@ Bry4n:添加了一些額外的C#代碼 – Andomar 2011-03-04 14:22:34

+0

我實際上已經注意到您不需要解析答覆,它已經解析爲JSON對象。你可以使用'webserviceReply.pageTitle'。我正在使用ASP.Net 3.5。 – cjbarth 2011-12-13 15:36:53

2
public class stuff { 
string pagetitle; 
string contentID; 
string nodeID; 
} 
[System.Web.Services.WebMethod] 
public static stuff EditPage(string nodeID) { 
... get the stuff 
    stuff returnme = new stuff(); 
    returnme.pagetitle = ... 
    returnme.contentid = ... 
    return returnme; 
} 

==== jQuery的一面: 假設你正在使用jQuery的AJAX調用做這樣的事情:

.ajax({ type: "GET", url: "./return.asmx", async: true, dataType: "xml", 
       success: function (respons, status) { 
$(respons).find("WebServiceCallName stuff pagetitle").text(); 
}}); 

你需要看看webservice的輸出直接(只要導航到它就好像它是一個網頁),以確保您的jQuery選擇器是正確的。