Ajax JSON空传递

时间:2017-01-13 10:23:32

标签: javascript jquery json ajax

致所有可能关注的人(我真的只是想要达到"请添加更多详细信息"限制)

当如下所示将数据传递到服务器时,正文显示为空。

服务器

<Button>

客户端

// POST method route
app.post('/pass', function (req, res) {
  console.log("server received POST from homepage")
  console.log(req.body)
  res.send('POST request to the homepage')
})

在这样传递(下面)时工作,但我更喜欢发送JSON数据而不是字符串

function ajaxJSONFunc(){
      var inputData = document.getElementById('input2').value

      var json = {"data":"abc"};

      $.ajax({
        url: "/pass",
        type: "POST",
        data: json
        contentType: "application/json",
        // dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
        success: function(data) {
         console.log("data passed back from server is:" + data)
        },
        error: function(err) {
           console.log("an error occured")
           console.log(err)
        }
      })
}

2 个答案:

答案 0 :(得分:1)

您定义了contentType: "application/json"。这意味着你必须发送一个json对象。

您必须使用JSON.stringify()方法。

data: JSON.stringify(json)

JSON.stringify函数将Javascript对象转换为JSON文本并将其存储在字符串中。

答案 1 :(得分:-1)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
 var json = "abc";
	$.ajax({
        url: "/pass",
        type: "POST",
        data: json,
        contentType: "application/json",
        // dataType: "json", only use if you need to responce data to be JSON, if its not JSON an error will fire when uncommented. defaults to text
        success: function(data) {
         console.log("data passed back from server is:" + data)
        },
        error: function(err) {
           console.log("an error occured")
           console.log(err)
        }
      });
});
</script>
</head>
<body>
</body>
</html>