gpt4 book ai didi

javascript - JQuery Ajax填充javascript变量问题

转载 作者:行者123 更新时间:2023-11-28 07:45:50 25 4
gpt4 key购买 nike

我尝试使用 JQuery Ajax 填充此格式的变量,但由于所有括号,我无法从后端返回该格式的数据

elements = [{ 
key: 1,
label: "Food",
open: false,
children: [
{ key: 211, label: "Burger" }
]
}];

这是我当前使用的代码,但不起作用

菜单.aspx:

$.ajax({
type: "POST",
url: "menu.aspx/get_menu",
data: {},
contentType: "application/json",
dataType: "json",
success: function (msg) {
$("#test").html(msg.d);
}
});

后端:

[WebMethod(EnableSession = false)]
public static string get_menu()
{
return "hello world";
}

最佳答案

您的后端代码应该看起来更像这样(在我的示例中为 WebService.cs,它是 WebService.asmx 的 CodeBehind):

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public class JsonResult
{
public string key, label, open;
public List<Children> children;
}
public class Children
{
public string key, label;
}

[WebMethod]
public List<JsonResult> test()
{
List<Children> child = new List<Children>();
child.Add(new Children
{
key = "211",
label = "Burger"
});

List<JsonResult> result = new List<JsonResult>();
result.Add(new JsonResult
{
key = "1",
label = "Food",
open = "false",
children = child
});
return result;
}
}

此代码以 JSON 形式发送创建的列表 - 当 jQuery 接收到它时,它看起来像这样:

{"d":[
{
"__type":"WebService+JsonResult",
"key":"1",
"label":"Food",
"open":"false",
"children":[
{
"key":"211",
"label":"Burger"
}
]
}
]}

然后,jQuery AJAX 就非常简单了,就像这样:

$.ajax({
type: "POST",
url: "/WebService.asmx/test",
contentType: "application/json",
success: function (response) {
var jsonResponse = response.d;
}
});

现在,您可以将每个元素作为 native JavaScript 对象进行访问,就像我在将每个对象分配给变量时在 success 回调中所示的那样。现在您可以对数据做任何您想做的事情。

success: function (response) {
var jsonResponse = response.d;
for (var i = 0; i < jsonResponse.length; i++) {
var key = jsonResponse[i].key;
var label = jsonResponse[i].label;
var open = jsonResponse[i].open;
var children = jsonResponse[i].children;
for (var a = 0; a < children.length; a++) {
var key = children[a].key;
var label = children[a].label;
}
}
}

这已经过 100% 测试并正常工作。如果还有什么可以帮助您的,请告诉我。

关于javascript - JQuery Ajax填充javascript变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27446435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com