在Ajax响应中,如果条件不起作用

问题描述

检查以下jquery代码。在此之后,处理后请求response返回no_file_found,但如果条件不满足且未达到alert()。我在这里做什么错了?

$("#btnFoo").on("click",function () {
            var file_data = $('#formUploadImg').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file',file_data);
            form_data.append('ProId',$(this).attr("img-upload-product-id"));
            $.ajax({
                url: '/mycontroller/upload',dataType: 'text',cache: false,contentType: false,processData: false,data: form_data,type: 'post',success: function (response) {
                    console.log(typeof response);//it returns string
                    if (response == "no_file_found") {
                        alert("this not hits");//this alert not hits
                    }
                    
                },error: function (response) {
                    alert("Error");
                }
            });
        });

请注意,我正在使用c#mvc5,并且响应来自mvc5控制器。下面是Mvc5示例:

[HttpPost]
public JsonResult upload()
{
    return Json("no_file_found");
}

解决方法

您需要使用.trim()功能来确保从spaces中删除所有不可见 response,以便能够match准确==的比较no_file_found

编辑:之所以not有效,是因为您返回的"no_file_found"加上了双引号“” 。但是在前端,您只需要检查no_file_found-您需要使用replace函数来确保所有双引号都是deleted中的response

var response = '"no_file_found"';
if (response.replace(/["']/g,"").trim() == "no_file_found") {
  alert("this hits"); //this alert hits
 }

,

这里的问题是您正在返回一个Json值-但您的ajax设置为具有dataType:“文本”。

如果您更改dataType:'json',则所有操作如预期。