2011-04-05 53 views
0

我使用了一些修改後的函數,它在幾個教程中重複使用,或者在某些論壇中用於回答。JQuery.getJSON和使用返回的數據

問題是,在通話功能之後,什麼也沒有發生。我調試它,並且JavaScript函數調用正確,Controller也調用正確,但我不這麼做,dropdownlist沒有更新。

看來問題是在嵌套到jQuery.getJSON的函數中的某個地方,但我不知道如何調試和檢查它,或者如何檢查數據是真正從服務器發送還是由客戶端捕獲。

的JavaScript:

function ConnectedEndPoint(href, SwitchId) { 
     jQuery.ajaxSetup({ cache: false }); 
     var id = jQuery(href).attr('id'); 
     var index = '_' + id.split('_')[1] + '_' + id.split('_')[2]; 
     jQuery.getJSON('/ActiveItem/Switches/ConnectedEndPoint/Switch/' + SwitchId, function (data) { 
      var items = "<OPTION>---------------------</OPTION>"; 
      jQuery.each(data, function (i, _switch) { 
       items += "<OPTION value='" + _switch.Value + "'>" + _switch.Text + "</OPTION>"; 
      }); 
      jQuery("#item_City" + index).html(items); 
     }); 
    }; 

控制器:

class mySwitchBoard 
    { 
     public string Text { get; set; } 
     public string Value { get; set; } 
    } 

    public JsonResult ConnectedEndPoint(string locality, int id) 
     { 
      IRepository<Switch> _SwitchRepository = new Repository<Switch>(); 
      Switch _Switch = _SwitchRepository.Get(id); 
      IList<mySwitchBoard> mySB = new List<mySwitchBoard>(); 
      foreach (SwitchBoard sb in _Switch.Location.ServerRoom.SwitchBoards) 
      { 
       mySB.Add(new mySwitchBoard() { Text = sb.Name, Value = sb.Id.ToString() }); 
      } 
      Repository).GetAllInServerRoom(2); 
      return Json(mySB); 
     } 

View是小通心粉代碼,但結果是這樣的:

<button name="itemUp_0_0" onclick="ConnectedEndPoint(this, 123)" type="button">Up</button><br> 
<select id="item_City_0_0" name="item_City_0_0"></select> 
+0

那是你的實際代碼?因爲它看起來像你有一個額外的行,那將是一個JavaScript錯誤,或至少結束你的功能比你想要的。 – tvanfosson 2011-04-05 14:24:14

+0

對不起,我做了一些複製粘貼後的外觀變化,我檢查了它 – Zdenek 2011-04-05 14:26:02

+0

您是否嘗試過使用FireBug調試Firefox並在getJSON回調中設置斷點以查看返回的數據?或IE開發人員工具,但我發現FF/FB更易於使用。 – tvanfosson 2011-04-05 14:29:08

回答

1

我相信你給的getJSON調用失敗因爲你試圖用它檢索的數據是不可序列化的。我知道IList不是,但你的mySwitchBoard應該是。嘗試將IList更改爲List。

下面的代碼應與調試

$.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) { 
     alert(textStatus); 
     alert(errorThrown); 
     alert(XMLHttpRequest.responseText); 
    }}); 
+0

非常感謝,IList是好的,但是這個javascript函數很有幫助。 – Zdenek 2011-04-06 06:33:23

0

問題是在控制器幫助:

... 
JsonResult jr = Json(mySB, JsonRequestBehavior.AllowGet); 
... 

JsonRequestBehavior未設置爲AllowGet