由于使用JQuery从服务器接收的数据是“ [object Object]的“类型”,因此使用JQuery转换来自服务器的数据时出现问题。
注意:从服务器接收的数据应该是JSON
我尝试将服务器的响应直接转换为JSON,但出现错误,因此我尝试先将响应转换为字符串,然后转换为JSON,但同样失败,代码如下:
mango
aaple
banana
orange
berry
// 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
});
});
预期结果是将数据转换为JSON字典
答案 0 :(得分:0)
使用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()
方法来检查对象中是否存在键。
答案 1 :(得分:0)
您的服务器已经在使用JSON发送响应,因此在前端(客户端)上,无需JSON.stringify()
响应,而在其上再次使用JSON.parse()
。
尝试记录数据,您应该能够使用数据响应直接访问状态和消息。
因此,请尝试从.js文件中删除以下行
let responseString = JSON.stringify(data);
相反,尝试
console.log(data.status);
console.log(data.message);
检查是否在浏览器控制台上获得了适当的日志。
答案 2 :(得分:0)
只要您的服务器返回有效的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请求: