[英]Correct way to handle the data from a post with JQuery
由於從服務器接收的數據是“類型”的[object Object],因此我在轉換帶有JQuery的帖子的服務器中的數據時遇到問題
注意:從服務器接收的數據應該是JSON
我嘗試將服務器的響應直接轉換為JSON,但出現錯誤,因此我嘗試先將響應轉換為字符串,然后轉換為JSON,但同樣失敗,代碼如下:
// THE FOLLOWING CODE IS FROM A HTML PAGE
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
let responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
/// THE FOLLOWING CODE IS FROM THE SERVER SIDE
res.json({
status: 'some status',
message: 'some message'
});
預期結果是將數據轉換為JSON字典
使用JSON.parse()
因此您的代碼將如下所示:
let responseJSON;
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
console.log(responseJSON.message);
if(responseJSON.hasOwnProperty('message') {
console.log(responseJSON['message']);
} else {
console.log("'message' not found in response");
}
兩者都會起作用。 如果用“字典”來表示具有唯一鍵的鍵值對,那么JSON對象鍵應該始終是唯一的。 您可以使用hasOwnProperty()
方法檢查對象中是否存在鍵,如上所述。
您的服務器已經使用JSON發送了響應,因此在前端(客戶端)上,無需JSON.stringify()
響應,也無需在其上再次使用JSON.parse()
。
嘗試記錄數據,您應該能夠使用數據響應直接訪問狀態和消息。
因此,請嘗試從您的.js文件中刪除以下行
let responseString = JSON.stringify(data);
相反,嘗試
console.log(data.status);
console.log(data.message);
檢查您是否在瀏覽器控制台上獲得了適當的日志。
只要您的服務器返回有效的JSON內容,那么jQuery POST返回的數據就是您不需要處理的JavaScript JSON對象,例如:
$.post(url, data, function(data, status, xhr) {
// data is a JSON object with the server response
let id = data.id;
alert("Your new post was saved with id: " + id);
});
請注意我如何直接訪問數據。
請檢查我為快速演示創建的這個簡單的jsfiddle; 它使用虛擬API發出POST請求:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.