Javascript 将Json对象从webMethod返回到Ajax调用
我遵循了Ajax调用方法和asp.net web方法 我的asp.net函数正在返回一些值,我需要这些值在Ajax调用中返回 我尝试了很多事情,但还没有成功 这是我的函数,我需要将我的列表转换为JSON:Javascript 将Json对象从webMethod返回到Ajax调用,javascript,c#,jquery,asp.net,ajax,Javascript,C#,Jquery,Asp.net,Ajax,我遵循了Ajax调用方法和asp.net web方法 我的asp.net函数正在返回一些值,我需要这些值在Ajax调用中返回 我尝试了很多事情,但还没有成功 这是我的函数,我需要将我的列表转换为JSON: public List < Node > ReadData() { SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrat
public List < Node > ReadData() {
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List < Node > list = new List < Node > ();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read()) {
list.Add(new Node {
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
**Jquery:**
$(function() {
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;
alert(typeof(data));
data = $.parseJSON(data);
alert(data.subject);
alert(data.description);
}
}
}; $.ajax(options);
});
});
public ListReadData(){
SqlConnection conn=newsqlconnection(“数据源=OUMAIMA-PC\\SQLEXPRESS;初始目录=AGIRH;集成安全性=True”);
string query=“从联合组织中选择uo、uo、RATTACHENT、lib和reduit”;
列表<节点>列表=新列表<节点>();
SqlCommand cmd=新的SqlCommand(查询,连接);
conn.Open();
SqlDataReader=cmd.ExecuteReader();
while(dataReader.Read()){
添加(新节点){
uo=dataReader.GetString(0),
uo_rattachement=dataReader.GetString(1),
lib_reduit=dataReader.GetString(2)
});
}
dataReader.Close();
康涅狄格州关闭();
退货清单;
}
**Jquery:**
$(函数(){
$.ajax({
类型:“POST”,
url:'WebForm1.aspx.cs/ReadData',
数据类型:“json”,
contentType:“应用程序/json;字符集=utf-8”,
成功:功能(响应){
if(response!=null&&response.d!=null){
var数据=响应d;
警报(数据类型);
data=$.parseJSON(数据);
警报(data.subject);
警报(数据.说明);
}
}
};$.ajax(选项);
});
});
这是我的源代码,我使用了webforms应用程序和orgchart.js库
此aspx.cs源代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testProjet
{
public partial class WebForm1 : System.Web.UI.Page
{
private object JsonConvert;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Nodes"] == null)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Node> list = new List<Node>();
list.Add(new Node
{
uo = "1",
lib_reduit = "Name 1"
});
Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
public static List<Node> ReadData()
{
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List<Node> list = new List<Node>();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list.Add(new Node
{
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
public static void Add(string uo, string uo_rattachement, string lib_reduit)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
list.Add(new Node
{
uo = uo,
uo_rattachement = uo_rattachement,
lib_reduit = lib_reduit
});
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Remove(string uo)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
Node removeItem = null;
foreach (var item in list)
{
if (item.uo == uo)
{
removeItem = item;
break;
}
}
list.Remove(removeItem);
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Update(Node oldNode, Node newNode)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
foreach (var item in list)
{
if (item.uo == newNode.uo)
{
item.uo_rattachement = newNode.uo_rattachement;
item.lib_reduit = newNode.lib_reduit;
break;
}
}
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Data.SqlClient;
使用System.Linq;
使用系统文本;
使用System.Web;
使用System.Web.Mvc;
使用System.Web.Script.Serialization;
使用System.Web.UI;
使用System.Web.UI.WebControl;
命名空间testProjet
{
公共部分类WebForm1:System.Web.UI.Page
{
私有对象JsonConvert;
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(!IsPostBack)
{
if(会话[“节点”]==null)
{
var jsonSerialization=new System.Web.Script.Serialization.JavaScriptSerializer();
列表=新列表();
添加(新节点)
{
uo=“1”,
lib_reduit=“名称1”
});
会话[“节点”]=jsonSerialization.Serialize(列表);
}
}
}
公共静态列表ReadData()
{
SqlConnection conn=newsqlconnection(“数据源=OUMAIMA-PC\\SQLEXPRESS;初始目录=AGIRH;集成安全性=True”);
string query=“从联合组织中选择uo、uo、RATTACHENT、lib和reduit”;
列表=新列表();
SqlCommand cmd=新的SqlCommand(查询,连接);
conn.Open();
SqlDataReader=cmd.ExecuteReader();
while(dataReader.Read())
{
添加(新节点)
{
uo=dataReader.GetString(0),
uo_rattachement=dataReader.GetString(1),
lib_reduit=dataReader.GetString(2)
});
}
dataReader.Close();
康涅狄格州关闭();
退货清单;
}
公共静态void Add(字符串uo、字符串uo\u rattachement、字符串lib\u reduit)
{
var jsonSerialization=new System.Web.Script.Serialization.JavaScriptSerializer();
var list=jsonSerialization.Deserialize((字符串)HttpContext.Current.Session[“节点]);
添加(新节点)
{
uo=uo,
uo_rattachement=uo_rattachement,
lib_reduit=lib_reduit
});
HttpContext.Current.Session[“节点”]=jsonSerialization.Serialize(列表);
}
公共静态无效删除(字符串uo)
{
var jsonSerialization=new System.Web.Script.Serialization.JavaScriptSerializer();
var list=jsonSerialization.Deserialize((字符串)HttpContext.Current.Session[“节点]);
节点removietem=null;
foreach(列表中的变量项)
{
如果(item.uo==uo)
{
removeItem=项目;
打破
}
}
列表。删除(removeItem);
HttpContext.Current.Session[“节点”]=jsonSerialization.Serialize(列表);
}
公共静态无效更新(节点oldNode、节点newNode)
{
var jsonSerialization=new System.Web.Script.Serialization.JavaScriptSerializer();
var list=jsonSerialization.Deserialize((字符串)HttpContext.Current.Session[“节点]);
foreach(列表中的变量项)
{
if(item.uo==newNode.uo)
{
item.uo_rattachement=newNode.uo_rattachement;
item.lib_reduit=newNode.lib_reduit;
打破
}
}
HttpContext.Current.Session[“节点”]=jsonSerialization.Serialize(列表);
}
}
}
这是我的aspc代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="testProjet.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title> OrgChart</title>
<script src="OrgChart.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#tree {
width: 100%;
height: 100%;
}
.field_0 {
font-family: Impact;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
<div id="tree">
</div>
</form>
<script >
var chart = new OrgChart(document.getElementById("tree"), {
nodeBinding: {
field_0: "UO",
field_1:"Uo_Rattachement"
},
menu: {
pdf: { text: "Export PDF" },
png: { text: "Export PNG" },
svg: { text: "Export SVG" },
csv: { text: "Export CSV" }
},
nodeContextMenu: {
edit: { text: "Edit", icon: OrgChart.icon.edit(18, 18, '#039BE5') },
add: { text: "Add", icon: OrgChart.icon.add(18, 18, '#FF8304') }
},
nodeMenu: {
details: { text: "Details" },
edit: { text: "Edit" },
add: { text: "Add" },
remove: { text: "Remove" }
}
});
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;//this data already json you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
};
chart.on('add', function (sender, n) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Add") %>',
data: JSON.stringify(n),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('remove', function (sender, uo) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Remove") %>',
data: JSON.stringify({ uo: uo }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('update', function (sender, oldNode, newNode) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Update") %>',
data: JSON.stringify({ oldNode: oldNode, newNode: newNode }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.load(<%= Session["Nodes"] %>);
});
</script>
<select style="position: absolute;right: 90px;top: 30px;color: #7a7a7a;font-size: 14px;padding: 10px;background-color: #F57C00;color: #ffffff;width: 100px;z-index:2;" id="selectTemplate">
<option>luba</option>
<option>olivia</option>
<option>derek</option>
<option>diva</option>
<option>mila</option>
<option>polina</option>
<option>mery</option>
<option>rony</option>
<option>belinda</option>
<option>ula</option>
<option>ana</option>
<option>isla</option>
<option>deborah</option>
</select>
</body>
</html>
组织机构图
html,正文{
宽度:100%;
身高:100%;
填充:0;
保证金:0;
溢出:隐藏;
}
#树{
宽度:100%;
身高:100%;
}
.field_0{
字体系列:影响;
}
var chart=新组织结构图(document.getElementById(“树”){
节点绑定:{
场_
[WebMethod()]
public static List<Node> ReadData()
{
//..
}
$.ajax({
type: "POST",
url: 'WebForm1.aspx/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;//this data already is json which represent list of Node so that you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
}
}
};
public JsonResult ReadData() {
// Rest of your code
return Json(new { data = list, subject = "My subject", description = "My Description" });
}
$(function () {
$.ajax({
type: "POST",
url: 'Home/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.data != null) {
var data = response.data;
alert(typeof (data));
alert('subject: ' + response.subject);
alert('description: ' + response.description);
}
}
})
});