繁体   English   中英

AJAX 请求返回“对象对象”

[英]AJAX request returning 'object object'

我一直在尝试并寻找解决方案,我有以下脚本但不幸的是,它返回object object作为回报

var states = (function () {
  var states = null;            
  $.ajax({                
    type: 'POST',
    'async': false,
    'global': false,
    'url': "../home/GetAllTags",
    'dataType': "json",
    'success': function (data) {                    
      states = data;
    }
  });
  return states;
})();  

我知道我可以做一个循环将它添加到字符串中,但我需要 Json,而不是字符串。 另外,我明确定义输出是 json 'dataType': "json",但我仍然不确定为什么我得到object object

任何的想法?

干杯

编辑:返回 json 的控制器

[HttpPost]
public JsonResult GetAllTags()
{
    List<Models.Tags.MTag> Tag_List = new List<Models.Tags.MTag>();
    Tag_List = GenerateList.Tags();
    var TAGS = Tag_List;
    return Json(TAGS.Select(t => new { id = t.Tag_id, val = t.Tag_name }), JsonRequestBehavior.AllowGet);
}

编辑 2 - 完整脚本

<script>

    $(function () {

        var substringMatcher = function (strs) {
            return function findMatches(q, cb) {
                var matches, substringRegex; 
                matches = [];
                substrRegex = new RegExp(q, 'i');
                $.each(strs, function (i, str) {
                    if (substrRegex.test(str)) {

                        matches.push({ value: str });
                    }
                });
                cb(matches);
            };
        };

        var states = (function () {
            var states = null;            
            $.ajax({                
                type: 'POST',
                //'async': false,
                'global': false,
                'url': "../my/GetAllTags",
                'dataType': "json",
                'success': function (data) {                    
                    states = data;
                }
            });
            return states;
        })();               

        alert(states);

        var tags = $('input.stateinput');
        tags.tagsinput();

        $(tags).each(function (i, o) {
            var taginput = $(o).tagsinput('input');
            taginput.typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
                autoselect: true
            }, {
                    name: 'states',
                    displayKey: 'value',
                    source: substringMatcher(states)
                }).bind('typeahead:selected', $.proxy(function (obj, datum) {                   
                    $(o).tagsinput('add', datum.value);
                    taginput.typeahead('val', '');
                }));
            $(taginput).blur(function () {
                taginput.typeahead('val', '');
            });
        });

    });



</script>

结果

在此处输入图片说明

正如我在评论中建议的那样,要转换:

[{"val":"tag1"},{"val":"tag2"},{"val":"testing"},{"val":"tes‌​t2"}]

到:

["tag1", "tag2","testing", "test2"]

您可以使用Array#map()

map()方法使用对调用数组中的每个元素调用提供的函数的结果创建一个新数组。

 var states = [{ "val": "tag1" }, { "val": "tag2" }, { "val": "testing" }, { "val": "test2 " }]; var result = states.map(function(x) { return x.val; }); console.log(result);

将 JSON 字符串解析为对象:

您可以使用JSON.parse()jQuery.parseJSON()

JSON.parse()

JSON.parse() 方法解析 JSON 字符串,构造字符串描述的 JavaScript 值或对象。 可以提供一个可选的 reviver 函数来在结果对象返回之前对其执行转换。

 var states = [{ val: "tag1" }, { val: "tag2" }, { val: "testing" }, { val: "test2" }]; console.log(typeof states); // => object states = JSON.stringify(states); console.log(typeof states); // => string states = JSON.parse(states); console.log(typeof states); // => object

jQuery.parseJSON()

采用格式良好的 JSON 字符串并返回结果 JavaScript 值。

 var states = [{ val: "tag1" }, { val: "tag2" }, { val: "testing" }, { val: "test2" }]; console.log(typeof states); // => object states = JSON.stringify(states); console.log(typeof states); // => string states = $.parseJSON(states); console.log(typeof states); // => object
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

所以最后:

 var states = [{ val: "tag1" }, { val: "tag2" }, { val: "testing" }, { val: "test2" }]; states = JSON.stringify(states); var newstates = $.parseJSON(states); var newstates3 = newstates.map(function(x) { return x.val; }); console.log(newstates3);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

JavaScript 数组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM