简体   繁体   English

将位置变量从Javascript传递到PHP函数

[英]Passing location variable from Javascript to PHP function

I'm using HTML5 geolocation and Javascript to do a reverse geolocation lookup with Google's API to get the town of the user. 我正在使用HTML5地理位置和Javascript通过Google的API进行反向地理位置查找,以获取用户所在地。 This all works fine, and I have the city/town stored in a JavaScript variable named city.short_name . 一切正常,我将城市/城镇存储在名为city.short_name的JavaScript变量中。

Now, I'm using wordpress and I'm trying to modify part of the content of my site using: 现在,我正在使用wordpress,并尝试使用以下方法修改网站的部分内容:

document.getElementById('contenttochange').innerHTML = <? echo do_shortcode('[<code here>]'); ?>;

Now if the content was just the same all the time, ie 现在,如果内容一直都是一样的,即

<? echo do_shortcode('[just_do_this]'); ?>

it would be fine, but unfortunately I need to add the town as a parameter called search . 很好,但是很遗憾,我需要将城镇添加为名为search的参数。 Eg 例如

<? echo do_shortcode('[just_do_this search="thetownofuser"]'); ?>

So, essentially, once I've found out the town and have it as a variable, is there any easy way for me to execute the PHP shortcode with that town as a parameter to replace the content I wish to? 因此,从本质上讲,一旦我找到城镇并将其作为变量,是否有任何简便的方法可以用该城镇作为参数执行PHP短代码来替换我想要的内容?

PHP is a Server-side Hypertext Preprocessor (actually the roots of the acronym "PHP"). PHP是服务器端超文本预处理器(实际上是缩写词“ PHP”的根)。 You cannot execute PHP from javascript, because PHP is not "active", to put it in one word. 您不能从javascript执行PHP,因为PHP不是“活动的”,所以只能用一个词来表达。

You send data to the server running PHP as a request , it gets processed through PHP, and out comes XHTML. 您将数据作为request发送到运行PHP的服务器,并通过PHP进行处理,然后出现XHTML。 All those <??> are rendered to their outputs before they are even sent to the client. 所有这些<??>甚至在发送到客户端之前都已呈现到其输出中。

The client ONLY deals with XHTML and Javascript (among other things, but for simplicity's sake) 客户端仅处理XHTML和Javascript(除其他事项外,为简单起见)

You can echo variables into your javascript, sure, because it is rendered to the document that is sent out the the client. 当然,您可以将变量回显到javascript中,因为它已呈现到客户端发送的文档中。 Once it reaches the client, PHP can no longer be used. 一旦到达客户端,便无法再使用PHP。

To send a variable to your PHP script, you will need to make an AJAX call and send the location variable as a part of your request. 要将变量发送到PHP脚本,您将需要进行AJAX调用并将location变量作为请求的一部分发送。

Alternatively, you could create a PHP script that has it's header's content-type set to text/javascript that takes in the variable in $_GET , and include it like so: 或者,您可以创建一个PHP脚本,将其标头的内容类型设置为text/javascript ,并在$_GET中接受变量,并像这样包含它:

<script type="text/javascript" src="setLocation.php?loc=<?= do_shortcode(/* Whatever */) ?>">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM