2016-03-12 146 views
-1

我是新手機差距應用程序開發和 我試圖從我的應用程序調用Web服務來從服務器獲取數據。 我成功地調用REST Web服務,但使用JavaScript解析JSON響應時出現問題。如何使用JavaScript解析json響應?

我用於調用服務的代碼如下:

 $.ajax({ 
        type: "POST", 
        url: "http://www.url.php", 
        contentType: "application/x-www-form-urlencoded", 
        data: dataString, 
        success: function(response) { 
         alert("success!"); 

        }, 
        error: function(request, status, error) { 
        console.log("Error status " + status); 
        console.log("Error request status text: " + request.statusText); 
        console.log("Error request status: " + request.status); 
        console.log("Error request response text: " + request.responseText); 
        console.log("Error response header: " + request.getAllResponseHeaders()); 
        } 
      }); 

我能夠得到的代碼的成功塊,但問題是我不能夠解析使用JavaScript的響應。 請指導或幫助我達成任務。

謝謝。

+0

您是否嘗試使用'JSON.parse'來解析反應? –

回答

0

我把它做如下:

 $.ajax({ 
        type: "POST", 
        url: "http://www.url.php", 
        contentType: "application/x-www-form-urlencoded", 
        data: dataString, 
        success: function(response) { 

        //entered in the success block means our service call is succeeded properly 

         var resp = JSON.stringify(response.text); // we are accessing the text from the json object(response) and then converting it in to the string format 
         console.log(JSON.stringify(response)); // print the response in console 
         alert(resp); // alert the response 

        }, 
        error: function(request, status, error) { 
        console.log("Error status " + status); 
        console.log("Error request status text: " + request.statusText); 
        console.log("Error request status: " + request.status); 
        console.log("Error request response text: " + request.responseText); 
        console.log("Error response header: " + request.getAllResponseHeaders()); 
        } 
      }); 

,你可以參考JSON對象:{ 「文」: 「登錄成功」, 「狀態」:1, 「school_detail_id」: 「72」 ,「data」:[{「section_id」:「541」,「class_name」:「1-A」},{「section_id」:「542」,「class_name」:「2-A」}]}

因此警報將顯示登錄成功/失敗。

0
success: function(response) { 
    var resp = JSON.parse(response); 
    alert(resp.text); // Login success or Fail 
} 
+1

雖然此代碼片段可能會解決問題,但[包括解釋](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – Will

+0

是的,先生,感謝您的意見! –