2017-10-16 42 views
0

對於愚蠢的問題感到抱歉。對於本機而言,我相對較新。我有抓取工作,所以我可以從服務器返回json響應。服務器API在出現錯誤時返回一個字符串,如果成功則返回一個json對象。有什麼辦法來比較響應,看看它的字符串或JSON變量?反應本機JSON響應檢查字符串或對象

不知道如何實現上述任何幫助,將不勝感激。

這裏是我的代碼

API.js

var API = { 

    SetupBuyOnline(email, serialNumber, platformType) { 
     var url = 'https://<urlomitted>/SetupBuyOnline'; 
     return fetch(url, { 
      method: 'GET', 
      headers: { 
       'Content-Type': 'application/json; charset=UTF-8', 
       'Accept': 'application/json', 
       'operating_system': platformType, 
       'email': email, 
       'serialNumber': serialNumber 
      } 
     }).then((res) => res.json()); 
    } 
    }; 

找到userScreen.js

findUserScreen(){ 
// this.props.navigation.navigate('JoinNowScreen') 
StudentApi.SetupBuyOnline('[email protected]', deviceId, "iOS") 
.then((responseData) => { 
    if(typeof(responseData) == 'string') 
    { 
    console.log('got api call ' + responseData); 
    alert('test = ' + responseData); 
    } 
    else 
    { 
    console.log('got api call ' + responseData); 
    alert(responseData); 
    } 
}) 

}

不知道我做錯了。在此先感謝

回答

2

除了更改=====(嚴格平等)並不多。但將與平常的正常工作。

不知道你在做什麼錯,因爲這段代碼工作得很好。

我會做什麼,而不是由具有JSON響應,像這樣

"{ error: true, }" "{ error: false, data: yourDataSentByTheServer! }" 這種方式,您只需要檢查是否有您的JSON響應裏面的錯誤性質。

function stringType(){ 
 
    const responseData = 'hello'; 
 
    if(typeof(responseData) === 'string') 
 
    { 
 
    console.log('got api call ' + responseData); 
 
    alert('test = ' + responseData); 
 
    } 
 
    else 
 
    { 
 
    console.log('got api call ' + responseData); 
 
    alert(responseData); 
 
    } 
 
} 
 

 
function objType(){ 
 
    const responseData = { 1:'hello', 2: 'koko' } 
 
    if(typeof(responseData) === 'string') 
 
    { 
 
    console.log('got api call ' + responseData); 
 
    alert('test = ' + responseData); 
 
    } 
 
    else 
 
    { 
 
    console.log('got api call ' + responseData); 
 
    alert(responseData); 
 
    } 
 
}
<button onClick="stringType();">Click me for string</button> 
 
<button onClick="objType();">Click me for obj</button>

+1

怪異。當我嘗試之前,它沒有檢測到它作爲一個字符串。無論如何感謝您的幫助:) – dogwasstar

+0

好吧:)但考慮我的選擇你的JSON,它是一個很好的方法來保持事物的簡潔:) – WilomGfx