首页 > 解决方案 > 如何将id从webmethod中的函数返回到javascript代码

问题描述

我有这个 javascript 函数来使用 JSON 插入数据

function Create(Name,Description) {
    var obj = {};
    obj.Name = Name;
    obj.Description = Description;
    $.ajax
        ({
            type: "Post",
            url: "/test.asmx/Create",
            dataType: 'JSON',
            contentType: "application/Json; Charset= Utf-8",
            data: JSON.stringify(obj),
            success: function () {
                alert("Great");
            },
            error: function (response) {
                alert(response);
            }
        });
}

WebMethod在我的网络服务中,我需要获取插入到我的 javascript 代码中的数据的 id

[WebMethod]
public int Create(string Name, string Description)
{
    try
    {
        var Qer = new DAL.MOD.TABLE1
        {
            kName = Name,
            Description = Description
        };
        t.Create(Qer);
        return Qer.Id;
    }
    catch
    {
        return -1;
    }
}

有没有人有任何建议如何实现这一目标?

标签: javascriptc#asp.netjsonweb-services

解决方案


好的,正如其他人指出的那样,您需要创建/设置/拥有一个在异步调用完成时被回调的函数。您可以使用内联函数()并且效果很好。所以一个全新的 function() 是动态创建的。

下一个?您不能只使用“响应”,而必须使用“.d”作为数据。

因此这将起作用:

   $.ajax({  
        type: "POST",  
        url: 'WebForm1.aspx/HelloWorld',
        contentType: "application/json",  
        datatype: "json",  
        success: function(responseFromServer) {  
            alert(responseFromServer.d)  
        }  
    });  
}  

注意 .d 从响应对象中获取数据。

如果你返回两个值?说这个:

[WebMethod()]
public static string[] HelloWorld()
{
string[] twovalues = new string[2];
twovalues[0] = "This is the first return value";
twovalues[1] = "This is the second return value";

return twovalues;

}

因此,现在您可以像这样获得两个返回值:

   $.ajax({  
        type: "POST",  
        url: 'WebForm1.aspx/HelloWorld',
        contentType: "application/json",  
        datatype: "text",  
        success: function(responseFromServer) {  
            alert(responseFromServer.d[0]);
            alert(responseFromServer.d[1]);
        }  
    });  

所以响应是一个返回的对象。您使用响应对象的“.d”方法来获取数据。并且如上所述,如果返回一个以上的值,那么您可以使用 [] 数组引用来提取/获取每个返回的值。


推荐阅读