簡體   English   中英

如何使用 JavaScript 解析 json 響應?

[英]How to parse json response using JavaScript?

我是電話間隙應用程序開發的新手,我正在嘗試從我的應用程序調用 Web 服務以從服務器獲取數據。 我成功調用了 REST Web 服務,但在使用 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 解析響應。 請指導或幫助我完成任務。

謝謝。

我按如下方式完成:

     $.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對象: {"text":"登錄成功","status":1,"school_detail_id":"72","data":[{"section_id":"541","class_name": "1-A"},{"section_id":"542","class_name":"2-A"}]}

所以警報將顯示登錄成功/失敗。

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

暫無
暫無

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

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