2017-01-13 7 views
2

のAjax JSON空通過

サーバー

// 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') 
}) 

クライアント

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) 
     } 
     }) 
} 

作品これ(下)のように渡して、私はJSONデータではなく、文字列

$.ajax({ 
    url: "/pass", 
    type: "POST", 
    data: inputData, 
    contentType: "application/x-www-form-urlencoded", 
    //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) 
    } 
    }) 
+1

この使用してみてください: 'データ:JSON.stringify(JSON)を'; –

+3

'JSONデータを送信し、文字列を送信したくないです.' JSON *は文字列であることに注意してください。 –

+0

サーバーコードに'(body-parser ') 'が必要ですか? –

答えて

1
を送信することを好むだろうというとき

あなたはd contentType: "application/json"。つまり、jsonオブジェクトを送信する必要があります。

JSON.stringify()メソッドを使用する必要があります。

data: JSON.stringify(json) 

JSON.stringify機能は、JSONテキスト文字列に保存するにJavaScriptオブジェクトをオンにします。

+1

私は本当に謝罪します - 私は本当にjQueryが自動的にそれをしたと思っています - これは正解です! - サーバーに 'bodyParser = require( 'body-parser')'と 'app.use(bodyParser.json());を含む限り、これが動作すると付け加えたいかもしれません。 –

+0

app.use(bodyParser.json( )); Hnngh私は間違ったパーサー、つまりapp.use(bodyParser.urlencoded({extended:true}))を使用していました。これが正しいかどうかは関係ありませんが、私は迷惑になり始めたばかりで、排除のプロセスを使用しようとしているだけのものを切ってみました。 – gxminbdd

-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"; 
 
\t $.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>

+0

** json ** –

+0

あなたが効果的に働いていることを示しています> – gxminbdd