利用php将javascript对象存储到mysql中

vyswwuz2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(301)

如何使用php将javascript对象保存到mysql?现在我正在使用googlemapapi,它会返回一个响应对象

directionsService.route({
    origin: document.getElementById('start').value,
    destination: document.getElementById('end').value,
    travelMode: 'BICYCLING'
}, function(response, status) {
    if (status === 'OK') {
        directionsDisplay.setDirections(response); //The Return Response
        //This function call ajax below to send response Obj with a key to store to MySQL
        storeRouteDB(storeLocations, response);
        showSteps(response, markerArray, display, map);
    } else {
        window.alert('Directions request failed due to ' + status);
    }
});

我使用ajax将objet发送到我的后端php

$.ajax({
    type: "GET",
    url: 'http://localhost:8080/storedRouteDB.php',
    async: false,
    data: {key: key, value: value},
    error: function(){
        console.log("Error in Ajax");
    },
    success: function (data) {
        result = data;
    }
});

在我的php中,我做到了:

$key = $_REQUEST['key'];
$value = $_REQUEST['value'];
echo checkDB($key, $value);
function checkDB($key, $value) {
    $dbServerName = "localhost";
    $dbUserName="root";
    $dbPassword="";
    $dbName="myDB";
    ....
    // Trying to zip the object to String and save it as char to MYSQL
    $value_zip = serialize($value);
    $sql = "INSERT INTO storedRoute (locations, objects) VALUES ('$key', '$value_zip')";

但我得到的结果是:

Uncaught TypeError: Cannot read property 'b' of undefined
at _.n.intersects (js?key=AIzaSyAbBYjTy8g4-dGYAl4_mHmWDVoWGEziq6c&callback=initMap:147)
at i (jquery.min.js:2)
at jt (jquery.min.js:2)
at jt (jquery.min.js:2)
at jt (jquery.min.js:2)
at jt (jquery.min.js:2)
at Object.<anonymous> (jquery.min.js:2)
at Function.each (jquery.min.js:2)
at jt (jquery.min.js:2)
at jt (jquery.min.js:2)

如何修复此错误?或者有没有其他更好的方法通过使用php将javascript对象存储到mysql?谢谢您!

siotufzp

siotufzp1#

我通常会这样做:

$.ajax({
    type: 'POST',
    url: 'http://localhost:8080/storedRouteDB.php',
    async: false,
    data: 'data='+JSON.stringify({key: key, value: value}),
    error: function(){
        console.log("Error in Ajax");
    },
    success: function (data) {
        result = data;
    }
});

然后可以访问中的对象 $_POST['data'] . 也许你也想用 json_decode . 让我知道它是否有用。

相关问题