首页 > 代码库 > MVC里的ajax

MVC里的ajax

视图界面代码:

@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <script src=http://www.mamicode.com/"~/js/jquery-1.7.1.min.js"></script>    <title>Login</title></head><body>    <div>        用户名:<input type="text" id="uname" /><br />        密码:<input type="text" id="pwd" /><br />        <input type="button" value=http://www.mamicode.com/"登陆" id="btn1" />    </div></body></html><script type="text/javascript">    $("#btn1").click(function () {        var a = $("#uname").val();        var b = $("#pwd").val();        $.ajax({            url: "/Ashxs/tttt.ashx",            data: { "uname": a, "pwd": b },            type: "post",            dataType: "json",            success: function (data) {                if (data.has == "1") {                    window.location.href = "Index";                }                else {                    alert(用户名密码输入有误!);                }            },            error: function () {                alert(服务器连接失败!);            }        });    });</script>

一般处理程序里的代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using Mvc1.Models;using System.Collections;namespace Mvc1.Ashxs{    public class Login : IHttpHandler    {        Data0425DataContext con = new Data0425DataContext();        public void ProcessRequest(HttpContext context)        {            string uname = context.Request["uname"].ToString();            string pwd = context.Request["pwd"].ToString();            string end = "";            Users uu = con.Users.Where(r => r.UserName == uname && r.PassWord == pwd).FirstOrDefault();            if (uu != null)            {                end = "{\"has\":\"1\"}";            }            else            {                end = "{\"has\":\"0\"}";            }            context.Response.Write(end);        }        public bool IsReusable        {            get            {                return false;            }        }    }}

控制器界面代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using Mvc1.Models;namespace Mvc1.Controllers{    public class HomeController : Controller    {public ActionResult Login()        {            return View();        }    }}

MVC里的ajax