2017年5月31日 星期三

【JQuery】Uncaught TypeError: Cannot use 'in' operator to search for 'length'

在 input select ajax 取回 json 要轉成 options 時噴
Uncaught TypeError: Cannot use 'in' operator to search for 'length'

在後端 return 是正確的 ["A123456789"],但前端要
  1. $.ajax({
  2. type: "POST",
  3. ...
  4. success: function (data) {
  5. $("#ddlTest").empty();
  6. $.each(data.d, function (i, value) {
  7. $("#ddlTest").append($("<option>").text(value).attr("value", value));
  8. });
  9. },
  10. ...
  11. });

問題其實很簡單,取回的 json 是 字串,不能直接使用,要 json2 之類的工具把它轉回陣列JSON.parse(data.d) 才能正確的 foreach。
  1. $.each(JSON.parse(data.d), function (i, value) {
  2. ...
  3. });

ref: SO
補充,ajax result => data.d 是 MS 的規格的樣子,參考: SO

沒有留言:

張貼留言