【问题标题】:Microsoft JScript runtime error: Object doesn't support property or method 'val'Microsoft JScript 运行时错误:对象不支持属性或方法“val”
【发布时间】:2014-02-18 12:14:28
【问题描述】:

我正在发出一个 json 请求,如果请求的结果为真,我希望显示一个特定的 div。

目前我收到以下错误,您能帮我解决一下吗?

Microsoft JScript 运行时错误:对象不支持属性或 方法'val'

p.s:我已经通过控制台检查了 json 是否正确返回“true”并且问题是成功的。

我附上下面的代码。

脚本:

<script type='text/javascript'>

    $(document).ready(function () {
        $('#ComputerLocation').hide();
        $('#typeddl').on('change', function () {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetItemTypeForm")',
                data: { itemTypeId: $('#typeddl').val() },
                success: function (result) {                 
                    if (result != null && result.val(this.Value) == 'true') {
                        $('#ComputerLocation').show();
                    };
                }
            });
         });
    });

</script>

控制器:

 [HttpPost]
        public JsonResult GetItemTypeForm(int itemTypeId)
        {
            //pseudo code
            var data = from s in db.ItemTypes
                       where s.ItemTypeId == itemTypeId 
                       select new { Value = s.IsComputer };

            return Json(data);
        }

【问题讨论】:

  • 我认为您错过了拼写 val,请尝试使用 value 代替

标签: c# asp.net ajax asp.net-mvc json


【解决方案1】:

如果我理解正确:

当你尝试在这一行获取 val()

(ifresult != null && result.val(this.Value) == 'true') {

您假设 result 有一个名为 val 的函数,但在 json 中您无法发送函数,而您正试图发送此函数 this.Value,这根本没有任何意义。

我假设你想:

if (result != null && result.val == 'true') {

在这一行中你也在使用this 我认为这也可能是错误的。在使用 ajax 回调之前,您应该将其设置为另一个字段。

<script type='text/javascript'>

    $(document).ready(function () {
        $('#ComputerLocation').hide();
        $('#typeddl').on('change', function () {
           var that = this; // now this is an jquery object
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetItemTypeForm")',
                data: { itemTypeId: $('#typeddl').val() },
                success: function (result) {                 
                    if (result != null && result.val ==  'true') { // maybe you want to check that.val()
                        $('#ComputerLocation').show();
                    };
                }
            });
         });
    });

【讨论】:

  • "result" 有对象 "Value" ,所以我想在 "Value" 为真时显示 div。
  • 所以这应该有效吗?也许只是写“ if ( result != null && result.Value === true) ..
  • hmmm ,我现在没有 javascript 错误,但它没有使 div 出现,尽管值为 true !
  • 调试时看到了什么? $('#ComputerLocation').show() 会运行吗?
  • 你在哪里查看它是否运行?我可以看到 json 发送 Value:true
猜你喜欢
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多