ajax json 根据邮政编码查地址

html:
<tr>
<td height="30" bgcolor="#DAEDFE">&nbsp;<strong>郵便番号:</strong></td>
<td height="30" bgcolor="#DAEDFE">&nbsp;
<s:textfield id="postCode" name="preKokyakuMBean.ko_post" maxLength="8" size="25" onblur="CtoH(this);value=value.replace(/[^\d|-]/g,'')"required="true" />
<input type="button" onClick="getAddressInfo()" name="addressSearch" style="width:100px;height:24px;" align="middle"value="住所検索">
</td></tr>

js:
/****************************************************************
* 機 能: 住所検索処理
* 引 数: postCode
* 戻り値:画面の住所(必須)(上)項目
****************************************************************/
function parseMessage(){
if(req.responseText == ''){
       alert('指定の郵便番号は不存在。');
       $("#postCode").focus();
        return false;
}
var result=eval(""+req.responseText+"");
var address=result[0].address;
var city=result[0].city;
var state=result[0].state;
var resultAddress=state+city+address;
if(resultAddress==null ||resultAddress==""){
alert('指定の郵便番号は不存在。');
  $("#postCode").attr("value","");
$("#postCode").focus();
return false;
}else{
    $("#add1").attr("value",resultAddress);
    }
}
function callback(){

    if(req.readyState == 4){
        if(req.status == 200){
            parseMessage();
        }
    }
}
function getAddressInfo(){
  var postCode = $("#postCode").val();
if(postCode == ''||postCode==null){
alert('郵便番号は「666-8888」まだは「6668888」ようなフォームで入力して下さい。');
$("#postCode").focus();
return false;
}
else{
var pattern=/^((^([0-9]{3})-([0-9]{4})$)|(^[0-9]{7}$))$/;
var result = pattern.test(postCode);
if(result == false){
alert('郵便番号は「666-8888」まだは「6668888」ようなフォームで入力して下さい。');
$("#postCode").attr("value","");
$("#postCode").focus();
return false;
  }
postCode= postCode.replace("-","");
}

var url=" searchAddressBack.action?postCode="+postCode;
if(window.XMLHttpRequest){
    req=new XMLHttpRequest();
}else if(window.ActiveXObject){
    req=new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
    req.open("GET",url,true);
    req.onreadystatechange=callback;
    req.send(null);
}
  }


配置文件 callContext.xml
<bean name="shiryouInputAction" scope="prototype"
class="jp.co.syspro.action.calldata.ShiryouInputAction">
<property name="shiryouInputService">
<ref local="shiryouInputService" />
</property>
</bean>

<bean id="shiryouInputService" scope="singleton"
class="jp.co.syspro.service.calldata.ShiryouInputService">
<property name="clientDaoImpl">
<ref local="clientDaoImpl" />
</property>
<property name="systen3DaoImpl">
<ref local="systen3DaoImpl" />
</property>
<property name="systen1DaoImpl">
<ref local="systen1DaoImpl" />
</property>
<property name="db" ref="DBCommon" />
</bean>

<bean id="system3DaoImpl" scope="singleton"
class="jp.co.syspro.persistence.sqlmapdao.Systen3DaoImpl">
</bean>
<bean id="clientDaoImpl" scope="singleton"
class="jp.co.syspro.persistence.sqlmapdao.ClientDaoImpl">
</bean>
<bean id="systen3DaoImpl" scope="singleton"
class="jp.co.syspro.persistence.sqlmapdao.Systen3DaoImpl">
</bean>
<bean id="systen1DaoImpl" scope="singleton"
class="jp.co.syspro.persistence.sqlmapdao.Systen1DaoImpl">
</bean>

struts-call-config.xml
<action name=" searchAddressBack" class="shiryouInputAction" method="getAddress">
<result type="json"/>
</action>

<action name=" changeCustGyoMClass" class="shiryouInputAction" method="changeCustGyoMClassList">
<result type="json"/>
</action>

ACTION:
  /**
     *
     * @description 住所検索処理
     * @return JSONString
     * @throws SQLException
     * @note なし
     */
    public String getAddress() {
       HttpServletRequest request = ServletActionContext.getRequest();
       String postCode = (String) request.getParameter("postCode");
       postCode = postCode.trim();
       String state = "";
        String city = "";
        String address = "";
     DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
     docBuilder = dbf.newDocumentBuilder();

  URL url = new URL("http://zip.cgis.biz/xml/zip.php?zn=" + postCode);

            InputStream inputStream = url.openStream();
            Document doc = docBuilder.parse(inputStream);

            Node node = null;
            Element root = doc.getDocumentElement();
            NodeList nodelist = root.getChildNodes();
            NodeList subNodelist = null;
            for (int i = 0; i < nodelist.getLength(); i++) {
                node = nodelist.item(i);
                String name = node.getNodeName();
                if ("ADDRESS_value".equals(name)) {
                    subNodelist = node.getChildNodes();
                    break;
                }
            }
            if (null != subNodelist) {
                for (int i = 0; i < subNodelist.getLength(); i++) {
                    node = subNodelist.item(i);
                    if (!node.hasAttributes()) {
                        continue;
                    }
                    NamedNodeMap nodeMap = node.getAttributes();

                    if (i == 9) {
                   state = nodeMap.getNamedItem("state").getTextContent();
                    } else if (i == 11) {
                        city = nodeMap.getNamedItem("city").getTextContent();
                    } else if (i == 13) {
                        address = nodeMap.getNamedItem("address").getTextContent();
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

       GetAddressTelNameInfoVO vo = new GetAddressTelNameInfoVO();
        vo.setAddress(address);
        vo.setCity(city);
        vo.setState(state);

        try {
            JsonUtil.sendJson(vo);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        }

        return null;
    }

sendJson方法的调用
package jp.co.syspro.common.util;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;

public class JsonUtil {
/**
* jsonデータ戻る
*
* @param obj
*            データ
* @throws IOException
*/
public static void sendJson(Object obj) throws IOException {
JSONArray json = JSONArray.fromObject(obj);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json.toString());
}

}

GetAddressTelNameInfoVO
public class GetAddressTelNameInfoVO implements Serializable {
    // TODO
    private static final long serialVersionUID = 1L;
    /**
     * 都道府県データ
     */
    private String state;
    /**
     * 市区郡データ
     */
    private String city;
    /**
     * 区町村データ
     */
    private String address;
    /**
     * 電話番号重複チェック結果
     */
    private String telCheckResult;
    /**
     * 資料収集者社員名
     */
    private String name;
   
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getTelCheckResult() {
        return telCheckResult;
    }

    public void setTelCheckResult(String telCheckResult) {
        this.telCheckResult = telCheckResult;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

追加一个联动
/****************************************************************
* 機 能: 業種大分類を変わったら、業種中分類を変わる処理 下拉框
* 戻り値: 業種中分類
****************************************************************/
jsp画面: 用的是s2标签
<td height="35" bgcolor="#DAEDFE">&nbsp;
<s:select id="gyosyu1" name="shiryouInputVO.gyosyu1" list="custGyoBClassList" listKey="id" listValue="name" headerKey="-99" headerValue=" " onchange="changeMClass();" required="true" />(大分類)
<s:select id="gyosyu" name="preKokyakuMBean.gyosyu" list="custGyoMClassList" listKey="id" listValue="name" required="true" />(中分類)</td>


js:
function parseMessage_changeMClass(){
if(req.responseText == ''){
        return false;
}
var result=eval(""+req.responseText+"");
    var select_root=document.getElementById('gyosyu');
          select_root.options.length=0;   
          for (var i = 0; i < result.length; i ++ ) {
              select_root.options[i] = new Option(
              result[i].name,
              result[i].id);
          }
var id=result[0].id;
var name=result[0].name;
    $("#gyosyu").attr("value",id);   
return true;
}
function callback_changeMClass(){

    if(req.readyState == 4){
        if(req.status == 200){
            parseMessage_changeMClass();
        }
    }
}
function changeMClass(){
   var gyosyu1 = $("#gyosyu1").val();
   var url="changeCustGyoMClass.action?selectedBClass="+gyosyu1;
if(window.XMLHttpRequest){
    req=new XMLHttpRequest();
}else if(window.ActiveXObject){
    req=new ActiveXObject("Microsoft.XMLHTTP");
}
if(req){
    req.open("GET",url,true);
    req.onreadystatechange=callback_changeMClass;
    req.send(null);
}

}
后台 :action
/**
     *
     * @description 大分類を変わった時、中分類リスト内容を変わる
     * @return JSONString
     * @throws SQLException
     * @throws NumberFormatException
     * @note なし
     */
    @SuppressWarnings("unchecked")
    public String changeCustGyoMClassList() throws NumberFormatException,
            SQLException {
        // セッションを取得する
Map session = ActionContext.getContext().getSession();
HttpServletRequest request = ServletActionContext.getRequest();
String selectedBClass = (String) request.getParameter("selectedBClass");
      
   String gyosyu1Name="";
        //セッションから業種(大分類)リストオブジェクトを取得する
  List<LabelValueBean> custGyoBClassAList = new ArrayList<LabelValueBean>();
custGyoBClassAList = (List<LabelValueBean>) session.get("custGyoBClassList");
  for (LabelValueBean entity : custGyoBClassAList) {
           String id = entity.getId();
            if (id.equals(selectedBClass)) {
                //選択した業種(大分類)名を取得
                gyosyu1Name = entity.getName();
                break;
            }
        }
  if(!gyosyu1Name.equals("")){
            // 業種:中分類リスト作成
    custGyoMClassList = shiryouInputService.getTblCustGyoMClass(Integer.parseInt(selectedBClass));     
        }else{
      LabelValueBean vo = custGyoBClassAList.get(0);
            // 大分類ディフォルト選定値を設定する
       selectedBClass = vo.getId();
            // 中分類リストを取得する
       custGyoMClassList = shiryouInputService.getTblCustGyoMClass(Integer.parseInt(selectedBClass)); 
        }
        session.put("custGyoMClassList", custGyoMClassList);
        try {
            JsonUtil.sendJson(custGyoMClassList);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error(e);
            }
        }
        return null;
    }

你可能感兴趣的:(Ajax,json,xml,struts,Microsoft)