2011-03-03 55 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选择器是正确的。