HMJING
**过程虽可贵,结果价更高**

后台代码:

namespace BaiduAPIDemo.Controllers
{
public static class ObjectExtentions
{
/// <summary>
/// 为Oject对象增加ToJsonString方法(注意对项目添加Newtonsoft.Json.dll引用)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonString(this Object obj)
{
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return JsonConvert.SerializeObject(obj, jsSettings);
}
}

public class HomeController : Controller
{

  public ActionResult TreeView()
  {
    return View();
  }

  public class Node

 {
  public int id;
  public int pp;
  public int pid;

}

public string Testback()
{
Node node = new Node();
node.id = 1;
node.pid = 2;
node.pp = 3;
Node node1 = new Node();
node1.id = 4;
node1.pid = 5;
node1.pp = 6;
List<Node> listnode = new List<Node>();
listnode.Add(node);
listnode.Add(node1);
var s = ObjectExtentions.ToJsonString(listnode);
return s;
}
}
}

前台代码:

<script>
function bt() {
$.ajax({
type: "GET",
url: "/Home/Testback",
data: {},

dataType: "text", //如果dataType是text(或者不指定类型时)转化时需加"(",例如(eval("(" + data + ")")),dataType是json时不加"(",例如 (eval(data))
success: function (data) {
alert(eval("(" + data + ")").pid); //如果传回来的是一个对象
alert(eval("(" + data + ")")[1].pid);//如果传回来的是一个list,可通过下标来解析
}

});
}
</script>
<input type="button" value="click" id="testbtn" onclick="bt()">

posted on 2015-12-23 10:16  HMJING  阅读(562)  评论(0编辑  收藏  举报