【问题标题】:Extract variable from Javascript to Python function从 Javascript 中提取变量到 Python 函数
【发布时间】:2017-12-25 10:41:44
【问题描述】:

我正在使用 PyQt5 创建一个小应用程序。在某些时候,我需要让用户从地图中选择纬度和经度。经过一些研究,实现地图搜索的最简单方法似乎是通过一些 Javascript 行使用谷歌地图。 我发现这段代码几乎可以满足我的需要:

https://gis.stackexchange.com/questions/33238/how-do-you-get-the-coordinates-from-a-click-or-drag-event-in-the-google-maps-api/33246#33246?newreg=eeb7c8c7ce344710838fba3d7b111d12

但是,我需要在我的 python 函数中使用用户选择的坐标。如何将 JavaScript 代码(“latLng”)中选择的纬度和经度传递给 python?我在许多论坛上阅读了一堆类似的问题,但我不知道如何解决我的问题。我希望找到一个非常简单的解决方案。 我的代码是这样的:

def latlong_function():

        html='''
 <html>  <head> ....  ....
'''

print(coordinates)

return html

【问题讨论】:

  • 我建议从 Javascript 向您的 Python 代码发送 AJAX 请求。然后python资源就可以返回你需要的值了。
  • 非常简单,真的:只需将 google.maps 加载到 QWebEngineView,然后使用带有回调的 runJavaScript 来获取值。
  • 这与我正在做的非常接近,但我如何获得回调?你有任何示例代码要发布吗?
  • @CarloBianchi。只要pass in a python function with one argument,就可以接收到javascript函数的返回值了。如果返回值是一个复杂的对象,你可以使用 json 对其进行字符串化。
  • 好吧,我知道什么是回调,但是我如何“接收 javascript 函数的返回值”。我的意思是,问题是:如何将信息从 Javascript 传递到 Python?此时似乎只有 AJAX 选项或类似选项。

标签: javascript python html google-maps pyqt5


【解决方案1】:

在为 web 应用程序做 python 后端时,我不是专家,但我确实有在 web 环境中使用 PHP 和 perl 的经验。

除非 python 有一个特定的实用程序/库来执行此操作(并且根据您的研究,它听起来好像没有)您最好的选择是让您的 JavaScript 使用类似 Ajax and JQuery 的东西通过 HTTP POST 请求提交数据.

这样的事情可能会奏效:

// Function called when an HTML button with id of "Search_Button" is clicked
$('#Search_Button').click(function () {

   // Get the values of your lat/long HTML inputs
   var lat = $('#Latitude_Input').val();
   var long = $('#Longitude_Input').val();

   // Submit the AJAX request
   $.ajax({
     url: "path/to/your_script.py", // Path of the python script to do the processing
     method: "POST", // Method to submit the HTTP request as, usually either POST or GET
     data: { // These are the POST parameters passed to the backend script
      latitude: lat,
      longitude: long 
     },
     success: function (returned_data) { // Function to run if successful, with the function parameter being the output of the url script
       alert('Here is the output: ' + returned_data);
     },
     error: function () { // Function to run if unsuccessful
       alert('An error occured');
     }
   });
});

这应该让您从 HTML 页面中获取数据并让您的 python 脚本处理它。

Check out this answer 用于在 python 中处理 POST/GET 请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2019-06-15
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多