[英]Pass javascript variable to php function using ajax in same file without page refresh
I am using PHP function to display geofences. 我正在使用PHP函数显示地理围栏。 I want to pass javascript variable to php function in same file without page refresh. 我想将JavaScript变量传递给同一文件中的php函数,而无需刷新页面。
function load(id,type){
if(type===2){
window.location.href="basic.php?idd=" + id; // i want to change code here
<?php
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
PHP function is: PHP函数是:
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($result)) {
$d[] = $myrow;
}
return $d; //returns result in array
}
javascript window.location.href
passes javascript value to php function but it reloads page also. javascript window.location.href
将javascript值传递给php函数,但也会重新加载页面。
If you're using jQuery, you can use $.ajax()
. 如果使用的是jQuery,则可以使用$.ajax()
。 It allows you to send data to your server and do something with the response. 它使您可以将数据发送到服务器,并对响应进行处理。
Eg: 例如:
$.ajax({
type: 'POST',
data: myvar
success: function(Response) { console.log(Response); }
});
will send myvar
to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console. 会将myvar
发送到您的服务器(当然需要进行一些参数调整),并记录服务器发送回浏览器控制台的所有内容。
Have a read of what you can do with jQuery. 阅读有关使用jQuery的知识。
You can do this using jQuery. 您可以使用jQuery完成此操作。 Basically you don't refresh the page, you just do an async query to the server and you get the response. 基本上,您无需刷新页面,只需对服务器执行异步查询即可获得响应。 In the following example the response is showed in alert box. 在以下示例中,响应显示在警报框中。
Your "index" file: 您的“索引”文件:
function load(id,type)
{
$.post("basic.php", { idd: idd }, function(data){
alert(data);
});
}
and basic.php 和basic.php
<?php
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($rs)) {
$d[] = $myrow;
}
return $d;
}
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.