0

I have a function that is called when a button is clicked, this function sends an ajax request using jquery. On success I have some logical if and else if statements. The web server can only send 2 types of text responses. It can either be "Success" or "Error". But when testing for these two conditions they seem to fail. I have added an else statement and an alert to tell me what the server is sending but just as I expected, it is either "Success" or "Error", the way I programmed my servlet in the server, it can only send "Success" or "Error" as response. Moreover my alert is spitting out "Success" or "Error" please I dont understand what is wrong here. please help.

 function deleteRecord(productID, description)
 {
    var errorMessage = '<td class="red-left">There was an error. <a href="">Please try again.</a></td>';
    var successMessage = '<td class="green-left">Product '+productID+' ('+description+') has been deleted sucessfully.</td>';
    var data = "productID="+productID+"&description="+description+"&deleteProduct=true";
    $.ajax({
        type: "GET",
        url: "deleteInventoryRecord.mpcs",
        data: data,
        cache: false,
        success: function(info)
        {
            if(info == 'Success')//This does not work
            {
                $(".green-left").replaceWith(successMessage);
                $("#message-green").fadeIn("slow");
                $("#product-"+productID).remove();
            }
            else if(info == 'Error')//This does not work
            {
                $(".red-left").replaceWith(errorMessage);
                $("#message-red").fadeIn("slow");
            } 
            else//This works always but I dont need it
            {
                alert(info); //It always says "Success" or "Error"
            }
        },
        dataType: 'text'
    });
 }

Here is the servlet code that sends the response:

private void deleteProduct(HttpServletResponse response, String productID) throws IOException
{
    try
    {
        response.setContentType("text/html");
        InventoryDAO iDao = new InventoryDAO();
        if(iDao.deleteProduct(productID) == true)
            response.getWriter().println("Success");
        else
            throw new RuntimeException("Error");
    }
    catch(ClassNotFoundException | IOException | SQLException | RuntimeException xcp)
    {
        response.getWriter().println("Error");
    }
}
4

2 回答 2

2

在这里暗中拍摄,并说服务器正在发送带有BOM的 UTF8 响应,这会导致您的比较失败。

要确认,请尝试alert(info.length)。“成功”应为 7,“错误”应为 5。如果不是,那么您可能有一个 BOM。

当然要检查的另一件事是响应中没有空格 - 同样,length检查将有助于验证这一点。

您可以通过将服务器端脚本编码为“不带 BOM 的 UTF8”来解决此问题,有时也称为“ANSI as UTF8”,具体取决于您的编辑器。或者,将您的if块更改为:

if( info.match(/Success$/)) ...
else if( info.match(/Error$/)) ...
于 2013-10-15T20:33:21.297 回答
1

您的deleteProduct方法设置了内容类型“text/html”,但您发送的是纯文本。这可能会使 jQuery 感到困惑,因为它会尝试info根据发送的内容类型标头来猜测 的类型。使用“text/plain”,甚至更好的“application/json”,这样您就可以向客户端发送更多信息。

于 2013-10-15T20:51:11.980 回答