【问题标题】:How to convert JSON to Jquery array in MVC ASp.Net如何在 MVC ASp.Net 中将 JSON 转换为 Jquery 数组
【发布时间】:2017-01-08 02:15:56
【问题描述】:

抱歉,问题太长了。我只是想弄清楚我在问什么。

我的控制器中有一个 JSON 结果:-

 public JsonResult Top7Video() 
    {
        db.Configuration.ProxyCreationEnabled = false;
        var result = (from v in db.TblVideos
                      orderby v.FileName
                       select new { title= v.FileName, artist=v.Artist,Image=v.Image,ID=v.ID}).Take(7).ToList();

        return Json(result,JsonRequestBehavior.AllowGet);
    }

在我的 Razor 视图中,我希望它是一个 JQuery 数组。我尝试了以下方法:-

<script type="text/jscript">

        var myarray = '{"title": "3. Ellie-Goulding","artist": "","mp4": "~/video/Ellie-Goulding.mp4","ogv": "~/video/Ellie-Goulding.ogv","webmv": "~/video/Ellie-Goulding.webm","poster": "~/video/VideoImg/play1.png"}';
        //var myarray = '{"Err0":"Only letters and white space allowed in Name"}';
        
        //alert(myarray);

        $(function () {
            $.ajax({
                type: "GET",
                url: "/Home/Top7Video",
                data:"{}",
                datatype: "Json",
                success: function (data) {
                    $.each(arr, function (index, value) {
                        myarray.push([',{ "title": "' + value.FileName + '", "artist": "' + value.Artists + '", "mp4": "~/video/' + value.FileName + '", "ogv": "~/video/' + value.FileName + '", "webmv": "~/video/' + value.FileName + '", "poster": "~/video/VideoImg/' + value.Image + '" }']);                       
                    });
                }
            });
        });


        var arr = $.parseJSON(myarray); //convert to javascript array
        alert(arr);


        $(function () {
            $.ajax({
                type: "GET",
                url: "/Home/Top7Video",
                datatype: "Json",
                success: function (data) {
                    $.each(data, function (index, value) {
                        $('#dropdownVideo').append('<li><div><a href="javascript:;" style="display: none;">×</a><a href="javascript:;" class="jp-playlist-item jp-playlist-current" tabindex="0">' + value.FileName + '<span class="jp-artist"> Song by ' + value.Artist + '</span></a></div></li>');
                    });

                }
            });
        });


        


        $(document).ready(function () {

            new jPlayerPlaylist({
                jPlayer: "#jquery_jplayer_1",
                cssSelectorAncestor: "#jp_container_1"
            },
                arr,
                {
                    swfPath: "../../dist/jplayer",
                    supplied: "webmv,ogv,mp4",
                    useStateClassSkin: true,
                    autoBlur: false,
                    smoothPlayBar: true,
                    keyEnabled: true
                });

        });



    </script>

Following is my HTML:-
<div class="video-main">
            <div class="video-record-list">
                <div id="jp_container_1" class="jp-video jp-video-270p" role="application" aria-label="media player">
                    <div class="jp-type-playlist">
                        <div id="jquery_jplayer_1" class="jp-jplayer" style="width: 480px; height: 270px;">
                            <img id="jp_poster_0" src="~/video/VideoImg/play2.png" style="width: 480px; height: 270px; display: inline;">
                            <video id="jp_video_0" preload="metadata" src="~/video/Ellie-Goulding.mp4" title="1. Ellie-Goulding" style="width: 0px; height: 0px;"></video>
                        </div>
                        <div class="jp-gui">
                            <div class="jp-video-play" style="display: block;">
                                <button class="jp-video-play-icon" role="button" tabindex="0">play</button>
                            </div>
                            <div class="jp-interface">
                                <div class="jp-progress">
                                    <div class="jp-seek-bar" style="width: 100%;">
                                        <div class="jp-play-bar" style="width: 0%;"></div>
                                    </div>
                                </div>
                                <div class="jp-current-time" role="timer" aria-label="time">00:00</div>
                                <div class="jp-duration" role="timer" aria-label="duration">00:30</div>
                                <div class="jp-controls-holder">
                                    <div class="jp-controls">
                                        <button class="jp-previous" role="button" tabindex="0">previous</button>
                                        <button class="jp-play" role="button" tabindex="0">play</button>
                                        <button class="jp-next" role="button" tabindex="0">next</button>
                                    </div>
                                    <div class="jp-volume-controls">
                                        <button class="jp-mute" role="button" tabindex="0">mute</button>
                                        <button class="jp-volume-max" role="button" tabindex="0">max volume</button>
                                        <div class="jp-volume-bar">
                                            <div class="jp-volume-bar-value" style="width: 100%;"></div>
                                        </div>
                                    </div>
                                    <div class="jp-toggles">

                                        <button class="jp-full-screen" role="button" tabindex="0">full screen</button>
                                    </div>
                                </div>
                                <div class="jp-details" style="display: none;">
                                    <div class="jp-title" aria-label="title">1. Ellie-Goulding</div>
                                </div>
                            </div>
                        </div>
                        <div class="jp-playlist">
                            <ul id="dropdownVideo" style="display: block;">
                                <li class="jp-playlist-current">
                                    <div>
                                        <a href="javascript:;" class="jp-playlist-item-remove" style="display: none;">×</a>
                                        <a href="javascript:;" class="jp-playlist-item jp-playlist-current" tabindex="0">
                                            1. Ellie-Goulding
                                            <span class="jp-artist">by Pixar</span>
                                        </a>
                                    </div>
                                </li>
                                
                            </ul>
                        </div>
                        <div class="jp-no-solution" style="display: none;">
                            <span>Update Required</span>
                            To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.
                        </div>
                    </div>
                </div>
            </div>
        </div>

我无法将 JSON 转换为 Jquery 数组。我收到以下错误:-

未捕获的类型错误:myarray.push 不是函数

我是 JSON 新手,在 How to response an array in json to jquery?How to convert Json object to Jquery Array? 上搜索了很多解决方案。但我无法解决这个问题。请帮忙!!

【问题讨论】:

  • myarray 是一个字符串,而不是一个数组。也许您的意思是使用括号[] 而不是引号''
  • data 已经是一个数组。如果您想要这些属性名称(titleartist 等),请修改您的控制器以发送具有这些属性名称的匿名对象集合 - select new { title = v.FileName, .... }
  • @David 使用 [] 代替 ' ' 也无济于事。我收到相同的错误消息和 alert(arr);我得到 [object] [Object]
  • @StephenMuecke 我根据您的建议编辑了我上面的问题。获得相同的错误消息和警报(arr);我得到 [object] [Object]
  • 你在哪里得到这个错误。你想在这里做什么?为什么要进行 2 次 ajax 调用来获取相同的数据,为什么还要使用 ajax 而不是最初将模型传递给视图

标签: jquery json asp.net-mvc


【解决方案1】:

添加这些行

myarray = JSON.parse(myarray);
myarray = [myarray];

在这条线下

var myarray = '{"title": "3. Ellie-Goulding","artist": "","mp4": "~/video/Ellie-Goulding.mp4","ogv": "~/video/Ellie-Goulding.ogv","webmv": "~/video/Ellie-Goulding.webm","poster": "~/video/VideoImg/play1.png"}';

myarray 是一个字符串。你不能推送字符串。

【讨论】:

  • 这样做我遇到了错误:- 未捕获的 SyntaxError: 位置 1 处 JSON 中的意外标记 o
【解决方案2】:

正如其他人在评论中提到的,下面的行不是一个数组

 var myarray = '{"title": "3. Ellie-Goulding","artist": "","mp4": "~/video/Ellie-Goulding.mp4","ogv": "~/video/Ellie-Goulding.ogv","webmv": "~/video/Ellie-Goulding.webm","poster": "~/video/VideoImg/play1.png"}';

但是一个字符串变量!您不能对此调用 push 方法。所以要做的第一件事就是把它变成一个合适的数组。您的操作方法将 json 数据返回一个集合。所以只需使用 $.each 循环遍历它。并根据需要从每个项目创建一个新的 js 对象并推送到数组。

var myarray =[]; // empty array
// If you want to have some default items, you can push here
myArray.push( { title : "Jon", artist:"Help"});

$(function () {
        $.ajax({
            type: "GET",
            url: "/Home/Top7Video"
            success: function (data) {
                $.each(arr, function (index, value) {
                    var item = { title:  value.FileName , 
                                 artist: value.Artists
                                 //to do : Add other properties here as well
                               };
                   //Now you can push this new item to the array
                   myarray.push(item);
                });
            }
        });
});

另外,就像评论中提到的斯蒂芬一样,您可以考虑从操作方法本身发送带有转换值的数组,而不是在您的 javascript 中进行字符串连接!

我还看到您正在进行 2 个调用,一个用于填充数组,另一个用于将项目添加到下拉列表中。既然你得到的是相同的数据,为什么不在同一个 ajax 调用的成功回调中做这两个?

【讨论】:

  • 对对!我想我正在取得一些进展。使用该代码,我将两个调用合并到一个 json 中,我的 #dropdownVideo 正在获取所需的详细信息,但没有数组。警报没有弹出,我收到了错误:- Uncaught SyntaxError: Unexpected end of JSON input。非常感谢您的帮助。
  • 数组现在看起来像:- var item = { title: value.FileName, artist: value.Artist, mp4: "~/video/" + value.FileName, ogv: "~/video/ " + value.FileName, webmv: "~/video/" + value.FileName, poster: "~/video/VideoImg/" + value.Image //to do : 在此处添加其他属性 }; myarray.push(item);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多