向AJAX请求返回一个空字符串

Return an empty string to an AJAX request

本文关键字:一个 字符串 AJAX 请求 返回      更新时间:2023-09-26

我有一个对函数的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]"。我如何在我的文本框中得到空字符串的结果?

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);
}

Try

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

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

更多信息在这里