javascript - 如何将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;
}
}
有没有人有任何建议如何实现这一目标?
解决方案
好的,正如其他人指出的那样,您需要创建/设置/拥有一个在异步调用完成时被回调的函数。您可以使用内联函数()并且效果很好。所以一个全新的 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”方法来获取数据。并且如上所述,如果返回一个以上的值,那么您可以使用 [] 数组引用来提取/获取每个返回的值。
推荐阅读
- python - 如何比较python中列表列表中的项目
- r - 克服错误:rstan::sampling()中的初始化失败
- maven - 所有 SoapUI 测试都没有从 Maven 构建中执行
- java - 使用 Fragments 时如何防止“IllegalStateException”
- javascript - 类实例不能传递给包含 Jasmine describe- 和 it-blocks 的函数
- python - 我可以抓取预下载的 .html 网页吗?如果是,如何?
- javascript - 如何修复节点 parent_id?
- wso2 - WSO2:避免在地址端点中硬编码 URI 端口
- apache - OpenProject 安装
- reactjs - 如何通过 react-bootstrap 验证表单控件以仅使用数值