$.ajax 和 $.post

$.post,$.ajax: 都是前台向后台发送异步请求

1.$.ajax

这个方法默认使用 GET 方式来传递的,如果[data]参数有传递数据进去,就会自动转换为POST方式的。

$(function () {
        var appointment = {
            Name: "galen.guo",
            Age: 20
        };
        $('#tty').click(function () {
            var url = 'TestJson';
            //前台向action传递一个json序列化对象
            $.ajax({
                url: '@Url.Action("TestJson")',
                type: 'POST',//指定以post方式
                data: JSON.stringify(appointment), //将对象序列化成json格式,不能省略
                dataType: 'json',//数据格式
                processData: false,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert('ok');
                }
            });
        });
    });

----processData:(默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

后台代码:

    public class Appointment
    {
        public String Name { get; set; }
        public String Age { get; set; }
    }

    [HttpPost]
    public JsonResult TestJson(Appointment app)
    {
          return Json("");
    }

 

2.$.post

原形:jQuery.post( url, [data], [callback], [type] ) :使用POST方式来进行异步请求

其中的[type]参数:(可选)Type of data to be sent, 默认是string,可以指定为JSON,XML,等

使用:$.post(url, { userId: userId, "key": keyValue }, function (data) { });//向action传递的参数是健值对的形式,data 就是action中返回的值,此例中就是"hello world"

其中url指定要调用的action,如'@Url.Action("Test")',

Test action 声明: 

[HttpPost]
public JsonResult Test(Int32 userId, String key)
{

    .........................

    return("hello world");

}

 

其实,$.post最终还是$.ajax实现的,源码如下:

     function (url, data, callback, type) {
        if (jQuery.isFunction(data)) {
            callback = data;
            data = {};
        }
        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });

posted on 2012-11-20 10:09  Gcam  阅读(450)  评论(0编辑  收藏  举报

导航