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

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

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

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

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

  1. $.ajax({
  2. type: "GET",
  3. url: 'http://localhost:8080/storedRouteDB.php',
  4. async: false,
  5. data: {key: key, value: value},
  6. error: function(){
  7. console.log("Error in Ajax");
  8. },
  9. success: function (data) {
  10. result = data;
  11. }
  12. });

在我的php中,我做到了:

  1. $key = $_REQUEST['key'];
  2. $value = $_REQUEST['value'];
  3. echo checkDB($key, $value);
  4. function checkDB($key, $value) {
  5. $dbServerName = "localhost";
  6. $dbUserName="root";
  7. $dbPassword="";
  8. $dbName="myDB";
  9. ....
  10. // Trying to zip the object to String and save it as char to MYSQL
  11. $value_zip = serialize($value);
  12. $sql = "INSERT INTO storedRoute (locations, objects) VALUES ('$key', '$value_zip')";

但我得到的结果是:

  1. Uncaught TypeError: Cannot read property 'b' of undefined
  2. at _.n.intersects (js?key=AIzaSyAbBYjTy8g4-dGYAl4_mHmWDVoWGEziq6c&callback=initMap:147)
  3. at i (jquery.min.js:2)
  4. at jt (jquery.min.js:2)
  5. at jt (jquery.min.js:2)
  6. at jt (jquery.min.js:2)
  7. at jt (jquery.min.js:2)
  8. at Object.<anonymous> (jquery.min.js:2)
  9. at Function.each (jquery.min.js:2)
  10. at jt (jquery.min.js:2)
  11. at jt (jquery.min.js:2)

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

siotufzp

siotufzp1#

我通常会这样做:

  1. $.ajax({
  2. type: 'POST',
  3. url: 'http://localhost:8080/storedRouteDB.php',
  4. async: false,
  5. data: 'data='+JSON.stringify({key: key, value: value}),
  6. error: function(){
  7. console.log("Error in Ajax");
  8. },
  9. success: function (data) {
  10. result = data;
  11. }
  12. });

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

相关问题