【问题标题】:Store Javascript Object to MySQL by using PHP使用 PHP 将 Javascript 对象存储到 MySQL
【发布时间】:2019-03-09 16:06:29
【问题描述】:

如何使用 PHP 将 Javascript 对象保存到 MySQL? 现在我使用谷歌地图 API,它返回一个响应对象

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?谢谢!

【问题讨论】:

  • 使用 Directions API 的应用程序受 Google Maps Platform 服务条款的约束。条款中的Section 3.2.4(a) 声明您不得预取、缓存、索引或存储任何内容,除非在条款中规定的有限条件下。

标签: javascript php jquery mysql google-maps-api-3


【解决方案1】:

我通常会这样做:

$.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 对其进行解码。让我知道它是否有效。

【讨论】:

  • "然后你可以访问 $_REQUEST['data'] 中的对象" $_REQUEST['data'] 这很糟糕,因为 $_REQUEST 设置了来自 GET、POST、COOKIE 数据的数据。使用$_GET['data'] 而不是$_REQUEST['data'].. $_REQUEST 数组或多或少像一个“全局”,我倾向于不惜一切代价避免。
  • 好吧,我会更新我的答案,也许删除 GET 类型并用 POST 替换它。谢谢
  • 另外,它不能跨 API 版本移植。
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多