【问题标题】:Correct way to handle the data from a post with JQuery使用 JQuery 处理来自帖子的数据的正确方法
【发布时间】:2019-11-16 11:30:32
【问题描述】:

我在使用 JQuery 将来自服务器的数据转换为 post 时遇到问题,因为从服务器接收到的数据是 [object Object] 的“类型”

注意:从服务器接收到的数据应该是 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 将 json 响应转换为 javascript 对象。
  • 是但不是,正如我在问题中提到的那样,我已经尝试过但不起作用
  • 服务器响应中缺少括号。请检查服务器是否返回格式正确的 json。
  • 对不起,我在问题中解决了这个问题,代码有相关的括号

标签: javascript jquery node.js post


【解决方案1】:

使用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() 方法检查对象中是否存在键。

【讨论】:

  • 这个答案很有用并且有效,但戴夫的答案更适合我的问题,因为它指出了我的错误,但无论如何非常感谢这个帮助
【解决方案2】:

您的服务器已经以 JSON 格式发送响应,因此在前端(客户端)不需要JSON.stringify() 响应并再次使用JSON.parse()

尝试记录数据,您应该可以直接使用数据响应访问状态和消息。

所以尝试从 .js 文件中删除以下行

let responseString = JSON.stringify(data);

相反,尝试

console.log(data.status);
console.log(data.message);

检查您是否在浏览器控制台上获得了相应的日志。

【讨论】:

    【解决方案3】:

    只要你的服务器返回的是有效的 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 请求:

    https://jsfiddle.net/danyalejandro/x46wzjdy/11/

    【讨论】:

    • 非常感谢丹妮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多