// 传过去一个简单值,获取一个简单值
$.ajax({
type: "GET",
url: '<%= Url.Action("xx", "Corp") %>',
data: "type=11",
success: function (msg) { alert(msg); }
});
public string xx()
{
string s = this.Request.QueryString["type"];
return s + ":ssssss";
}
// 获取一个复杂值
$.ajax({
url: '<%= Url.Action("xx", "Corp") %>',
type: "POST",
success: function(data) {
var obj = eval("(" + data + ")");
alert(obj.name);
}
});
// 这样更方便。
$.ajax({
url: '<%= Url.Action("xx", "Corp") %>',
type: "POST",
dataType:"json",
success: function(data) {
alert(data.name);
}
}); public ActionResult xx()
{
return this.Json( new
{
name = "Dr.Worm",
worm = "Programer"
} );
}
// 传过去一个复杂值,获取一个复杂值
$.ajax({
url: '<%= Url.Action("xx", "Corp") %>',
type: "POST",
dataType: "json",
data: "ID=1&FirstName=C&LastName=HY",
success: function(data) {
alert(data.ID + data.FirstName + data.LastName);
}
});
public JsonResult xx( FormCollection form )
{
return Json( new
{
ID = int.Parse(this.Request.Form[ "ID" ] ),
FirstName = "w:" + this.Request.Form[ "FirstName" ],
LastName = "s:" + this.Request.Form[ "LastName" ]
} );
}

客户端调用方式:

$("#ButAjax").click(function() {
$.ajax({
type: "POST", //默认是GET
url: "/AjaxTest/getPerson",
data: "ID=1&FirstName=C&LastName=HY",
async: true, //异步
cache: false, //不加载缓存
success: function(obj) {
alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
},
error: function() {
alert("请求失败");
}
});
});
$("#ButAjax2").click(function() {
$.ajax({
type: "POST", //默认是GET
url: "/AjaxTest/getPerson2?ID=3&FirstName=C&LastName=HY",
async: true, //异步
cache: false, //不加载缓存
success: function(obj) {
alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
},
error: function() {
alert("请求失败");
}
});
});
$("#ButAjax3").click(function() {
$.ajax({
type: "POST", //默认是GET
url: "/AjaxTest/getString",
async: true, //异步
cache: false, //不加载缓存
success: function(str) {
alert(str);
},
error: function() {
alert("请求失败");
}
});
});
$("#ButAjax4").click(function() {
$.ajax({
type: "POST", //默认是GET
url: "/AjaxTest/getJsonString",
async: true, //异步
cache: false, //不加载缓存
success: function(str) {
var obj = eval(str);
$.each(obj, function(item, value) {
alert(item + ":" + obj[item]);
});
},
error: function() {
alert("请求失败");
}
});
});
//================================================================
$("#ButJson1").click(function() {
$.getJSON("/AjaxTest/getJson1", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
alert(json);
$.each(json, function(item, value) {
alert(item + ":" + json[item]);
});
});
});
$("#ButJson2").click(function() {
$.getJSON("/AjaxTest/getJson2", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
alert(json);
$.each(json, function(item, value) {
alert(item + ":" + json[item]);
});
});
});
$("#ButJson3").click(function() {
$.getJSON("/AjaxTest/getJson3", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
alert(json);
$.each(json, function(item, value) {
alert(item + ":" + json[item]);
});
});
});
$("#ButJson4").click(function() {
$.getJSON("/AjaxTest/getJsonSerializingJson", { ID: "22", FirstName: "C1", LastName: "HY1" }, function(json) {
alert(json);
$.each(json, function(item, value) {
alert(item + ":" + json[item]);
});
});
});
$("#ButJson5").click(function() {
$.getJSON("/AjaxTest/getJsonDeSerializingJson", { json: '{"ID":201,"FirstName":"C","LastName":"HY","Man":true}' }, function(json) {
alert(json);
$.each(json, function(item, value) {
alert(item + ":" + json[item]);
});
});
});
//================================================================
$("#ButSerializing").click(function() {
$.ajax({
type: "POST",
url: "/AjaxTest/testSerializingJson",
data: "ID=101&FirstName=C&LastName=HY&Man=false",
async: true,
cache: false,
success: function(obj) {
alert(obj);
},
error: function() {
alert("请求失败");
}
});
});
$("#ButDeSerializing").click(function() {
$.ajax({
type: "POST",
url: "/AjaxTest/testDeSerializingJson",
data: 'json={"ID":201,"FirstName":"C","LastName":"HY","Man":true}',
async: true,
cache: false,
success: function(obj) {
alert(obj.ID + obj.FirstName + obj.LastName + obj.Man);
},
error: function() {
alert("请求失败");
}
});
});
$("#ButSerializingList").click(function() {
$.ajax({
type: "POST",
url: "/AjaxTest/serializingList",
data: "",
async: true,
cache: false,
success: function(obj) {
alert(obj + "length:" + obj.length);
$.each(obj, function() {
$.each(this, function(item, value) {
alert(item + ":" + json[item]);
});
});
},
error: function() {
alert("请求失败");
}
});
});

Controllers 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication.Controllers
{
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Man { get; set; }
}
public class AjaxTestController : Controller
{
#region ===============$.Ajax测试=================
/// <summary>
/// 测试返回对象
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public JsonResult getPerson(FormCollection form)
{
Person p = new Person
{
ID = int.Parse(form["ID"]),
FirstName = form["FirstName"],
LastName = form["LastName"]
};
return Json(p);
}
/// <summary>
/// 经测试发现:当Global中定义{controller}/{action}/{id}时
/// 前台url?ID=3&FirstName=C&LastName=HY传到后台时ID值为""
/// 所以把Global中定义为{controller}/{action}/{uid}
/// </summary>
/// <param name="ID"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public JsonResult getPerson2(string ID, string FirstName, string LastName)
{
Person p = new Person
{
ID = int.Parse(ID),
FirstName = FirstName,
LastName = LastName
};
return Json(p);
}
/// <summary>
/// 测试返回字符串
/// </summary>
/// <returns></returns>
public ContentResult getString()
{
return Content("{id:'2',FirstName:'C',LastName:'HY'}");
}
/// <summary>
/// 测试返回json字符串
/// </summary>
/// <returns></returns>
public ContentResult getJsonString()
{
return Content("({id:'2',FirstName:'C',LastName:'HY'})");
}
#endregion
#region ==============$.getJSON(返回json格式测试)============
/// <summary>
/// 经测试发现必须是双引号(")不能是单引号(')
/// </summary>
/// <param name="Code"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public ContentResult getJson1(string ID, string FirstName, string LastName)
{
return Content("{/"id/":1,/"name/":/"chy/",/"flag/":true}");
}
/// <summary>
/// 经测试发现必须是双引号(")不能是单引号(')
/// </summary>
/// <param name="Code"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public ContentResult getJson2(string ID, string FirstName, string LastName)
{
return Content("{/"id/":/"/",/"name/":/"chy/"}");
}
/// <summary>
/// 经测试发现必须是双引号(")不能是单引号(')
/// 产生错误前台没反应
/// </summary>
/// <param name="Code"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public ContentResult getJson3(string ID, string FirstName, string LastName)
{
return Content("{'id':'3'}");
}
#endregion
#region============Newtonsoft.Json.dll(json序列化和反序列化测试)=============
/// <summary>
/// $.Ajax序列化Json
/// </summary>
/// <param name="ID"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public ContentResult testSerializingJson(FormCollection form)
{
Person p = new Person
{
ID = int.Parse(form["ID"]),
FirstName = form["FirstName"],
LastName = form["LastName"]
};
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
} /// <summary>
/// $.Ajax反序列化json
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public JsonResult testDeSerializingJson(FormCollection form)
{
Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(form["json"].ToString());
return Json(p);
}
/// <summary>
/// $.getJSON序列化Json
/// </summary>
/// <param name="ID"></param>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
/// <returns></returns>
public ContentResult getJsonSerializingJson(string ID, string FirstName, string LastName)
{
Person p = new Person
{
ID = int.Parse(ID),
FirstName = FirstName,
LastName = LastName
};
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
}
/// <summary>
/// $.getJSON反序列化json
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public ContentResult getJsonDeSerializingJson(string json)
{
Person p = Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(json);
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(p));
}
#endregion
#region================返回集合================
public JsonResult serializingList()
{
List<Person> ls = new List<Person>();
ls.Add(new Person
{
ID = ,
FirstName = "C",
LastName = "HY",
Man = false
});
ls.Add(new Person
{
ID = ,
FirstName = "Z",
LastName = "JJ",
Man = true
});
return Json(ls);
}
public JsonResult deSerializingList(string json)
{
List<Person> listP = new List<Person>();
List<string> listStr = json.Split(',').ToList<string>();
foreach (string s in listStr)
{
listP.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<Person>(s));
}
return Json(listP);
}
#endregion
}
}

MVC+jquery+AJAX的几种方式的更多相关文章

  1. (转载)MVC + JQUERY + AJAX的几种方式

    MVC + JQUERY + AJAX的几种方式 // 传过去一个简单值,获取一个简单值 $.ajax({            type: "GET",         url: ...

  2. 通过XMLHttpRequest和jQuery实现ajax的几种方式

    AJAX大家已经都知道了,是为了实现异步通讯,提高用户体验度,而将很多旧知识(XML,DOM,JavaScript,HTML,Jquery,Css……)重新融合的一个新的知识框架.而,XMLHttpR ...

  3. C# MVC 实现登录的5种方式

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷.  学无止境,精益求精    小弟之前做过三月的MVC,后来又一直webFo ...

  4. Struts2实现ajax的两种方式

    基于Struts2框架下实现Ajax有两种方式,第一种是原声的方式,另外一种是struts2自带的一个插件. js部分调用方式是一样的: JS代码: function testAjax() { var ...

  5. Spring MVC处理异常的4种方式

    http://blog.csdn.net/ufo2910628/article/details/40399539 http://my.oschina.net/CandyDesire/blog/3333 ...

  6. MVC日期格式化的2种方式

    原文:MVC日期格式化的2种方式 假设有这样的一个类,包含DateTime类型属性,在编辑的时候,如何使JoinTime显示成我们期望的格式呢? using System; using System. ...

  7. mvc jquery ajax传递数组null问题

    mvc jquery ajax传递数,  areaIds是个int数组.后台action用list<int>接收.当我想传空值时,先用null传递,结果action收到的AreaIds竟然 ...

  8. JQuery 提供了两种方式来阻止事件冒泡。

    JQuery 提供了两种方式来阻止事件冒泡. 方式一:event.stopPropagation(); $("#div1").mousedown(function(event){ ...

  9. Checkbox框全选操作,form表单提交与jquery ajax提交两种处理方式

    //1.jquery ajax<script type="text/javascript"> $(function(){ var basePath = $(" ...

随机推荐

  1. HDU 2040 亲和数 [补] 分类: ACM 2015-06-25 23:10 10人阅读 评论(0) 收藏

    今天和昨天都没有做题,昨天是因为复习太累后面忘了,今天也是上午考毛概,下午又忙着复习计算机图形学,晚上也是忘了结果打了暗黑3,把暗黑3 打通关了,以后都不会玩太多游戏了,争取明天做3题把题目补上,拖越 ...

  2. 思科ASA系列防火墙配置手册

    使用console连接线登录方法 1.使用cisco的console连接线,连接设备的console口和计算机com口(笔记本用USB转COM口连接线)2.使用超级终端或secureCRT软件连接设备 ...

  3. HTML5简介及HTML5的发展前景

    WEB技术发展越来越迅速,HTML5的到来更是把WEB技术推向了巅峰,目前HTML5技术已经日趋成熟,不仅在PC段,HTML5更是在移动终端上也有广泛的应用,HTML5的未来十分光明,值得我们去学习. ...

  4. conn,stmt,rset 的关闭(规范)

    Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = dataSource.getCon ...

  5. web.xml 详解

    http://xmlns.jcp.org/xml/ns/javaee 重定向为 http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javae ...

  6. thinkphp显示重复两次

    在index.php中去掉 //App::run(); 这种方式是原来的旧版本的方式,现有版本的Thinkphp已经改变,不需要输入此行即可运行.

  7. .net 学习资源(转)

      名称:快速入门地址:http://chs.gotdotnet.com/quickstart/描述:本站点是微软.NET技术的快速入门网站,我们不必再安装.NET Framework中的快速入门示例 ...

  8. easyui 表单和自定义验证扩展和js自定义返回值

    ================jsp==========================<form  method="post" id="regfrminp&qu ...

  9. ELF--动态链接

    对前面add.c稍作修改, #include <stdio.h>int add_count = 0; extern int sum_count;extern void print_log( ...

  10. mongo常用命令

    1.由于mongo没有关系型数据库常用,一些基础的命令容易忘记 db.table.update( { "_id" : xxx } , { $set : { "field1 ...