在 Ajax 响应中,我的 if 条件不起作用
In Ajax response my if condition is not working
检查下面的 jquery
代码。这里在进程 post 请求 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
函数来确保所有双引号都是 response
.[=23= 中的 deleted
]
var response = '"no_file_found"';
if (response.replace(/["']/g, "").trim() == "no_file_found") {
alert("this hits"); //this alert hits
}
这里的问题是您正在返回一个 Json 值 - 但您的 ajax 设置为具有数据类型:'text'.
如果您更改数据类型:'json' 一切如预期。
检查下面的 jquery
代码。这里在进程 post 请求 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
函数来确保所有双引号都是 response
.[=23= 中的 deleted
]
var response = '"no_file_found"';
if (response.replace(/["']/g, "").trim() == "no_file_found") {
alert("this hits"); //this alert hits
}
这里的问题是您正在返回一个 Json 值 - 但您的 ajax 设置为具有数据类型:'text'.
如果您更改数据类型:'json' 一切如预期。