现在的位置: 首页 > 综合 > 正文

ajax实现无刷新省市联动

2017年12月18日 ⁄ 综合 ⁄ 共 3441字 ⁄ 字号 评论关闭

Common.js文件提供了两个函数一个是$函数,实现根据id返回对应的Dom对象,另外一个就是http函数,实现向服务器发送XMLHttpRequest请求

function $(id) {
    return document.getElementById(id);
}
(function (window) {

    //options:{url,async,data,type,successCallback,errorCallback,contentType}
    //contentType若省略,则其值为application/x-www-form-urlencoded
    var http = function (options) {
        options = options || {};
        var httpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Miscrosoft.xmlhttp");
        httpRequest.onreadystatechange = function () {
          
            switch (httpRequest.readyState) {
                case 1:
                    break;
                case 2: break;
                case 3: break;
                case 4:
                    if (httpRequest.status === 200) {
                        if (options.successCallback) {
                            options.successCallback(httpRequest.responseText);
                        }
                    }
                    else {
                        options.errorCallback(httpRequest.responseText);
                    }
                    break;
            }
        }
        httpRequest.open(options.type, options.url, options.async);
        if (!options.contentType) {
            httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        else {
            httpRequest.setRequestHeader("Content-Type", options.contentType);
        }
        httpRequest.send(options.data);
 
    }
    window.http = http;
})(window);

另一个就是aspx页,没有后台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="C01无刷新省市联动.aspx.cs" Inherits="interview_web.无刷新省市联动" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="Common.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript">
        http({
            type: "post",
            url: "C01无刷新省市联动.ashx",
            data: "action=GetAllProvince",
            successCallback: function (data) {
                if (data) {
                    var province = $("province");
                    data = JSON.parse(data);//转换为json数组
                    for (var i = 0; i < data.length; i++) {
                        province.options.add(new Option(data[i].AreaName, data[i].AreaId));
                    }
                    province.onchange = function () {
                        var selectProvince = province[province.selectedIndex].value;
                        getCity(selectProvince);
                       
                    }
                    province.selectedIndex = 1;
                    getCity(province[province.selectedIndex].value);
                }
            },
            errorCallback: function (data) {
                alert(data);
            },
            async: true
        });

        function getCity(province) {
            http(
                {
                    type: "post",
                    url: "C01无刷新省市联动.ashx",
                    data: "action=GetCity&province=" + province,
                    successCallback: function (data) {
                        data = JSON.parse(data);//转换为json数组
                        var city = $("city");
                        city.options.length = 0;
                        if (data) {
                            for (var i = 0; i < data.length; i++) {
                                city.options.add(new Option(data[i].AreaName, data[i].AreaId));
                            }
                        }
                    },
                    errorCallback: function (data) {
                    },
                    async:true
                });
        }

    </script>
    <style type="text/css">
        #province
        {
            width:150px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <select id="province" >
                <option></option>
            </select>
            <select id="city">
                <option></option>
            </select>
        </div>
    </form>
</body>
</html>

还有一个是一般处理程序,

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace interview_web
{
    /// <summary>
    /// C01无刷新省市联动 的摘要说明
    /// </summary>
    public class C01无刷新省市联动 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request.Form["action"];
            if (action == "GetAllProvince")
            {
                context.Response.Write(GetAllProvince());
            }
            else if (action == "GetCity")
            {
                string city = context.Request.Form["province"];
                context.Response.Write(GetCity(city));
            }

        }
        string GetAllProvince()
        {
            List<Area> province = Helper.DbHelperSql.ExecuteList<Area>("select * from tblarea where areapid=0");
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize(province);
        }
        string GetCity(string areaId)
        {
            List<Area> city = Helper.DbHelperSql.ExecuteList<Area>("select * from tblarea where areapid=@areaId", new SqlParameter("@areaId", areaId));
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize(city);

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

抱歉!评论已关闭.