【问题标题】:Return an empty string to an AJAX request向 AJAX 请求返回一个空字符串
【发布时间】:2011-09-14 02:04:30
【问题描述】:

我有一个对函数的 AJAX 调用:

$('#DeviceType').change(function () {
   // when the selection of the device type drop down changes 
   // get the new value
   var devicetype = $(this).val();

   $.ajax({
      url: '@Url.Action("GetEquipmentCode")',
      type: 'POST',
      data: { deviceTypeID: devicetype },
      success: function (result) {
         // when the AJAX succeeds refresh the EquipmentCode text box
         $('#EquipmentCode').val(result);
      }
   });
});

函数是

[HttpPost]
public string GetEquipmentCode(int deviceTypeID)
{
   var deviceType = _db.DeviceTypes.Single(d => d.ID == deviceTypeID);

   return (deviceType.EquipmentCode != null) ? 
                      deviceType.EquipmentCode.Code : 
                      String.Empty;
}

但是,如果函数返回String.Empty,我在文本框中实际得到的字符串是“[object XMLDocument]”。如何在我的文本框中得到空字符串的结果?

【问题讨论】:

  • AJAX 响应应该是 XML 还是 JSON?这是来自 WCF 还是 MVC ActionMethod?
  • MVC 动作方法。还有 XML 或 JSON - 也许这就是我应该返回的而不是字符串?

标签: javascript jquery asp.net-mvc ajax


【解决方案1】:

JSON 可能是最简单的。

试试:

$('#DeviceType').change(function () {
   // when the selection of the device type drop down changes 
   // get the new value
   var devicetype = $(this).val();

   $.ajax({
      url: '@Url.Action("GetEquipmentCode")',
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      data: { deviceTypeID: devicetype },
      success: function (result) {
         // when the AJAX succeeds refresh the EquipmentCode text box
         $('#EquipmentCode').val(result);
      }
   });
});

然后在你的 ActionMethod 中

[HttpPost]
public ActionResult GetEquipmentCode(int deviceTypeID)
{
   var deviceType = _db.DeviceTypes.Single(d => d.ID == deviceTypeID);

   return Json((deviceType.EquipmentCode != null) ? 
                      deviceType.EquipmentCode.Code : 
                      String.Empty);
}

【讨论】:

    【解决方案2】:

    试试

      .... 
      data: { deviceTypeID: devicetype },
      dataType : 'html',
      ...
    

    默认情况下,jquery 会尝试猜测,有时可能不准确。

    More info here

    【讨论】:

    • 刚刚将"text" 更改为“html”
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多