打开了一个websocket隧道,无法在console.log上查看json数据,现在我想将该数据流保存在本地,基本上保存在mysql数据库中。我用Ajax和php编写应用程序代码。
JavaScript代码:
stomp.connect(headers, function(cb) {
//Subscribe to a 3rd party
var topic = stomp.subscribe('/destination', function(e) {
var mes = e;
var body = JSON.parse(e.body);
//Insert Data to mySQL
function jsRecordInsertWrite(){
var jsObject = {
"Time": document.body.timestamp.value,
"SourceId": document.body.sourceId.value,
"TrackingId": document.body.trackingId.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'send.php',
dataType : 'json',
contentType: 'application/json',
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
}, headers);
});
PHP脚本:
<?php
//Creating a connection
$link = mysql_connect('localhost', 'root', '','test');\
//read the json file contents
$id = $_GET['id'];
$timestamp = $_POST['Time'];
$sourceId = $_POST['SourceId'];
$trackingId = $_POST['TrackingId'];
//insert into mysql table
$sql = "INSERT INTO tbl_Data(id, Time, SourceId, TrackingId)
VALUES(NULL,'$timestamp', '$sourceId', $trackingId')";
if(!mysql_query($sql)) {
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
?>