簡體   English   中英

為什么獲取響應中的字符串比較無法正常工作?

[英]Why is my string comparison in fetch response not working properly?

基本上,我將草稿的ID發布到服務器以使用獲取功能刪除草稿,並且如果成功,服務器將響應成功文本。 這是我的代碼。

fetch(this.url + "/vue/api/processdraft?action=delete&id=" + item.id, {
    method: "POST"
})
    .then(response => {
        return response.text();
    })
    .then(function (response) {
        console.log(response);
        if (response === "success") {
            console.log("Test");
            this.draftList.splice(index, 1);
        }
    });

在上面的代碼中,在console.log(response)中顯示了預期的成功 但是if塊中的代碼不起作用。 而且我不知道這是怎么回事? 它甚至不會按預期方式打印測試 這是輸出的屏幕截圖。

在此處輸入圖片說明

而且我還檢查了響應文本前后是否有空格,如果有關系的話。

編輯:我檢查了服務器端的空格,雖然我確保沒有空格,但忘記了換行符。 因此,已使用答案建議的trim()解決了此問題。

控制台中可能會有您看不到的字符(換行符,空格等)。 要顯示它們,可以使用JSON.stringify

  console.log(" success\\n"); // success, right? console.log(JSON.stringify(" success\\n")); // no, not quite ... 

要在忽略空格和換行符時進行匹配,請使用response.trim() === "success"response.includes("success")

您可以嘗試使用tim():

.then(function (response) {
    console.log(response);
    if (response.trim() === "success") {
        console.log("Test");
        this.draftList.splice(index, 1);
    }
});

希望它能工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM