0

我在将变量发布到php脚本并在不刷新页面的情况下返回结果时遇到问题。php脚本koord.php经过测试,运行良好。

这是我的 js 代码(adresa, mjesto 和coords是文本输入框):

$(document).ready(function () {
    $('#coord_click').click(function () {
        provjera();
    });
});

function provjera() {

    var adresa = $('#adresa').val();
    var mjesto = $('#mjesto').val();
    var puna_adresa = adresa + " " + mjesto;

    $.post("koord.php", { puna_adresa: puna_adresa },function (result) {
        $('#coords').val(result);
    });
}

koord.php:

$puna_adresa = $_GET['puna_adresa']; 

function getCoordinates($address){ 
    $address = str_replace(" ", "+", $address); 
    $url = "maps.google.com/maps/api/geocode/…"; 
    $response = file_get_contents($url); 
    $json = json_decode($response,TRUE); 

    return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geo‌​metry']['location']['lng']); 
} 

echo getCoordinates($puna_adresa);   

完整的源代码在这里: http: //pastebin.com/u/bradetic

谢谢!

4

4 回答 4

1

你真的需要使用 Jquery AJAX,这里有一个例子:

<script>

function your_function()
{

// collect data like this
var formData = jQuery("#your_form_id").serializeArray();

jQuery.ajax({  
    type: "POST",  
    url:"your_php_page.php",  
    data:formData,
    dataType:'json',

    beforeSend: function()
    {
    },
    success: function(resp)
    {  

        alert(resp);

    }, 
    complete: function()
    {
    },
    error: function(e)
    {  
        alert('Error: ' + e); 
    }  
}); 

}

</script>

你的 PHP 脚本应该是这样的:

$puna_adresa=$_POST['puna_adresa']; 

function getCoordinates($address){ 
$address = str_replace(" ", "+", $address); 
$url = "maps.google.com/maps/api/geocode/…;; 
$response = file_get_contents($url); 
return $response;
} 

$response = getCoordinates($puna_adresa);

echo json_encode($response);
于 2013-11-13T07:07:26.060 回答
1

Jquery POST 不是问题。

你正在做$.post(...)这意味着你需要在koord.phpvia中获取参数$_POST,并且你正在使用$_GET,你看到问题了吗?

解决方案

更改$_GET['puna_adresa'];$_POST['puna_adresa'];

或者

在您的客户端更改$.post(...)$.get(...)

POST你知道和对的区别GET吗?

于 2013-11-13T07:18:24.263 回答
0

你可以试试这个,

     $.post("koord.php", { puna_adresa: adresa, mjesto: mjesto }, function (result) {
        $('#coords').val(result);
    });

其他方式:

    $.post("koord.php", $( "#testform" ).serialize(), function (result) {
        $('#coords').val(result);
    });

参考:http ://api.jquery.com/jQuery.post/

于 2013-11-13T06:59:29.580 回答
0

你可以试试这个

$.post( "koord.php", $( "#testform" ).serialize() );
于 2013-11-13T08:36:32.623 回答