2016-09-09 41 views
1

你好所以我試圖解析,我得到一次我使用HTTP Web請求頁碼請求予以幫助它似乎每次失敗我:/JavaScript如何解析數字?

代碼,我使用,使Web請求和解析:

var xhr = new XMLHttpRequest(); 
xhr.open('GET', "website url", true); 
xhr.send(); 

xhr.onreadystatechange = processRequest; 

function processRequest(e) { 
    if (xhr.readyState == 4 && xhr.status == 200) { 
     var response = JSON.parse(xhr.responseText); 
      alert(response.); 
    } 
} 

我不知道我需要寫後點我試過很多選項:(

反應的例子,我得到:{「地位」:1,「請求」:「1663758118」}

我只需要取得數字

HTML:

<pre>{"status":1,"request":"1663758118"}</pre> 

所以,如果有人可以幫助將是巨大的:)

+0

「我只需要得到數字」 - 你是什麼意思?你想要的輸出是什麼? – Santi

+1

使用response.request –

+0

這個? 'JSON.parse(響應).request' –

回答

0

如果我正確理解你的問題,你的代碼不正確地解析JSON字符串成JSON對象,那麼你就可以執行以下操作以從JSON對象中檢索數據

response.status // '1' as int 
response.request // "1663758118" as string 

希望這回答可以幫助你:)

0

在點之後,您需要輸入屬性名稱才能獲取值。

如果你需要一個字符串轉換爲數字,你可以添加一個+字符串前立即簽署:

var response = JSON.parse('{"status":1,"request":"1663758118"}'); 
 

 
var stat = +response["status"]; 
 
var req = +response["request"]; 
 

 
console.log('status is: ' + stat + ' typeof is: ' + typeof stat); 
 
console.log('request is: ' + req + ' typeof is: ' + typeof req);

0

如果你從你的反應{"status":1,"request":"1663758118"}需要的數字,你可以用做這

const response = {"status":1,"request":"1663758118"} 
 
const values = Object.keys(response).map(key => parseInt(response[key], 10)) 
 
console.log(values) // => [1, 1663758118]