MVC ajax 返回字符串作为 [object] 对象

MVC*_*bie 1 ajax asp.net-mvc jquery

这是我的 ajax 代码,它提交带有文件的表单数据。如果我总是删除我的自定义字符串“has”文件,它将起作用并返回“1234567”。我期望返回“has file 1234567”,但总是抛出[object]对象

 $( document ).ready(function() {
     $('#scan').change(function (e) {
         debugger

         var element = this;
         var formData = new FormData();
         var totalFiles = document.getElementById("scan").files.length;

         var file = document.getElementById("scan").files[0];
         formData.append("scan", file);
         $.ajax({
             url: '@Url.Action("scancode", "Products")',
             type: "POST",
             dataType: "json",
             data: formData,
             processData: false,
             contentType: false,
             success: function (data) {

                 $('#barcode').val(data);                   
             },
             error: function (err) {

                 document.getElementById('emsg').innerHTML = err;
             }
         });
     });
});
Run Code Online (Sandbox Code Playgroud)

控制器

 public string scancode(HttpPostedFileBase scan) {
        var str = "";
        if (scan !=null)
        {
            str = "has file";
        }

        try
        {


        IBarcodeReader reader = new BarcodeReader();
        // load a bitmap
        var barcodeBitmap = (Bitmap)Bitmap.FromStream(scan.InputStream);
        // detect and decode the barcode inside the bitmap
        var result = reader.Decode(barcodeBitmap);
        // do something with the result
        if (result != null)
        {
            str =str+ result.Text;
        }
        }
        catch (Exception ex)
        {

            str = ex.Message;
        }
        return str;
    }
Run Code Online (Sandbox Code Playgroud)

ViV*_*iVi 5

您必须始终JsonResult从控制器返回 a 到 ajax 查询。JsonResult只需使用以下命令将字符串转换为Json(stringvalue);

你的代码将变成:

public JsonResult scancode(HttpPostedFileBase scan) 
{
    var str = "";
    if (scan !=null)
    {   
        str = "has file";
    }
    try
    {
        IBarcodeReader reader = new BarcodeReader();
        // load a bitmap
        var barcodeBitmap = (Bitmap)Bitmap.FromStream(scan.InputStream);
        // detect and decode the barcode inside the bitmap
        var result = reader.Decode(barcodeBitmap);
        // do something with the result
        if (result != null)
        {
            str =str+ result.Text;
        }
    }
    catch (Exception ex)
    {
        str = ex.Message;
    }
    return Json(str);
}
Run Code Online (Sandbox Code Playgroud)