JQuery跨域解決方案

来源:互联网 发布:婴儿床上装饰 知乎 编辑:程序博客网 时间:2024/05/22 07:48
1.相關JS代碼
<script type="text/javascript">
 $(document).ready(function(){
        //begin 縣市
        $("#iSearch_countyId1").change(function(){

             $.getJSON("http://www.cthouse.com.tw/New/GetTownshipSelectOptionJson.ashx?ct_parent=" + $("#iSearch_countyId1").val() + "&jsoncallback=?", function(data){
                //var result = eval("(" + data + ")");
                
                $.each(data, function(i,n){
                    //alert(n);
                     $("#iSearch_townshipId1").empty();
                     $("#iSearch_townshipId1").append(n);
                });
                
                
                
             });
            
        });
   });
</script>

2.相關HTML代碼
  <select id="iSearch_countyId1" name="countyId1" >
               <%= iSearchUtil.getCityTownList("0", "", 1, 1, iSearch)%>
  </select>
 <select id="iSearch_townshipId1" name="townshipId1">
            <option>全部</option>
 </select>

3.後台ashx代碼

<%@ WebHandler Language="C#" Class="GetTownshipSelectOptionJson" %>

using System;
using System.Web;

public class GetTownshipSelectOptionJson : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");

        string ct_parent = context.Request.QueryString["ct_parent"];
        string default_val = context.Request.QueryString["default_val"];
        string jsoncallback = context.Request.QueryString["jsoncallback"];
        string options = CascadeUtility.GetCodeCityTownOptions(ct_parent, "");
        string json = jsoncallback + "(";
       
        json += "{\"options\":\"" + options.Replace("\"", "\\\"").Replace("\n", "\\n") + "\"}";
        json += ")";
        //json = jsoncallback + "({\"options\":\"aaa\\\"aaa\"})";
        context.Response.Write(json);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

說明
$.getJSON()方法裡,跨域一定要注意 jsoncallback=? 參數,它會自動生成一個字符串,後台返回的JSON字符串必須以它命名。
0 0
原创粉丝点击