getJSON 和 parseJSON


<script src="@Url.Content("~/Scripts/jquery.json-2.3.min.js")" type="text/javascript"></script>


@using (Html.BeginForm("ForList", "CSOT", FormMethod.Post))
{
    <div>
        <fieldset>
            <legend>CSOT List Type</legend>
            <p>
                Please select the target item in the dropdown box:
            </p>
            <div id="list" class="editor-label">
            </div>
            <div class="editor-label">
            <input type="submit" style = "width:200px" value="Continue"/>
            </div>
         </fieldset>
     </div>
}


<script type="text/javascript">

        //獲取JSON字符串,創建 select 標簽
        $.getJSON("ForListTypeValue", function (data) {

          

           //如果 data 是 JSON 字符串, 必須將它轉換為對象字面量
            var objJSON= $.parseJSON(data);


            var selectItems = "";
            $.each(objJSON.listtype, function (i, item) {
                selectItems += '<option value="' + item.value+ '">' + item.text+ '</option>';
            });
            selectItems = '<select id="listType">' + selectItems + '</select>';

 

            //添加 select 標簽
            $("#list").html(selectItems);
        });
</script>

 

===========================================================

 

public ActionResult ForListTypeValue()
{

            //以JSON字符串作參數,比較特殊,在 callback function 中,需要對data進行 $.parseJSON(data)
            return Json("{\"listtype\":[" + string.Join<string>(",", new Models.CSOTModel(Server.MapPath("~")).ListType.Select(n =>  "{\"text\":\""+n.Text+"\",\"value\":\""+n.Value+"\"}")) + "]}", JsonRequestBehavior.AllowGet);
}

 

但正常情況下,JsonResult 是將對象(非JSON字符串)轉換為JSON字符串,並且Response.ContentType="application/json",

這樣在callback function 中的 data 就是對象字面量,不需要再使用 $.parseJSON(data) 進行轉換。

如果Response.ContentType="text/plain",則不能再進行轉換為JSON字符串,

而是直接輸出,在 callback function 中 也不需要對data 進行 $.parseJSON(data)。

 (ContentType是什么在$.getJSON中沒什么效果,而在$.ajax中就有作用了)

自定義ActionResult:

public class StringResult:ActionResult
    {
        string _data { get; set; }

        public StringResult(string data)
        {
            _data = data;
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if(context==null)
                throw new NotImplementedException();

            context.HttpContext.Response.ContentType = "text/plain";

            //JsonResult中使用的序列化,在這不能使用

            //JavaScriptSerializer serializer = new JavaScriptSerializer();

            //context.HttpContext.Response.Write(serializer.Serialize(_data)); 轉換為JSON字符串

            context.HttpContext.Response.Write(_data);   //直接輸出    

         }
    }

 

這樣可以修改為:

public ActionResult ForListTypeValue()
{

        return new StringResult("{\"listtype\":[" + string.Join<string>(",", new Models.CSOTModel(Server.MapPath("~")).ListType.Select(n =>  "{\"text\":\""+n.Text+"\",\"value\":\""+n.Value+"\"}")) + "]}");
}

 

也要修改 callback function 中的

var objJSON= $.parseJSON(data);

var objJSON= data;

 

再次請求, $.getJSON 會取緩存數據,如果需要取消數據輸出緩存,則在Action上加上

[OutputCache(Duration = 0, VaryByParam = "None")]


 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM