簡體   English   中英

從 getJson 調用中獲取響應文本

[英]Getting the response text from a getJson call

我正在嘗試實現一個 function ,它將根據某個 ajax 調用給出的響應文本來做一些事情。 但我無法訪問響應文本字段。 這是我的代碼:

               var response = $.getJSON('/add_participant',{
                email : uemail,
                password : upassword
               })

我試圖以這種方式訪問它:

response.responseText

但是當我將它注銷到控制台時,它說它是未定義的。

我認為這與在訪問響應文本之前需要先解決的 ajax 調用有關。 那是因為如果我將它保存到一個全局變量中,當我拉起網頁並使用檢查工具時,我就能夠以這種方式訪問 responseText。

如何在我的 function 期間獲得該響應文本? 有沒有辦法讓腳本等待它解決或其他什么?

提前致謝!

由於這是異步執行的,因此您需要在.done回調中處理它。 這是示例代碼。

var response = null; // assign to [] if you think you will receive an array
$.getJSON('/add_participant',{
  email : uemail,
  password : upassword
}).done(function (data) {
  response = data;
  console.log('response: ', data);
})

嘿,我發現我的代碼出了什么問題,實際上是我調用的 python 代碼有問題。 I'm setting up my website with the Flask library in Python, and I was using the ajax call to use a python function in the back end and get the output it returned. 問題是當我在 python function 中返回 output 時,我返回的是一個字符串,就像這樣:

return ("It worked!")

function 的 rest 仍在運行並做我想讓它做的事情,當我使用檢查工具時仍然可以查看響應。 但返回值的格式不正確。 It seems that this resulted in something along the lines of the Javascript code on the front end not getting the message from Python that the Python function had finished. 因此, .done(function (data) { } )塊中的任何內容都不會被執行。

為了解決這個問題,我不得不返回一個 jsonified 字典。 jsonify 是來自 flask 庫的 function。 這是它的外觀:

return(jsonify({'result': 'It worked!'}))

然后,如果您想在 javascript 中訪問該數據,請訪問.done(function (data) { } )塊內數據 object 的結果屬性。 對我來說,它看起來像這樣:

var response = $.getJSON('/add_participant',{
                email : uemail,
                password : upassword
               }).done(function (data) {
                if (data.result ='It Worked!'){
                    console.log("It worked!!");
                    // Do whatever else you wanted

                }
                else{
                    console.log("It didn't work.");
                    // Do something else
                }


                })

暫無
暫無

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

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