>我在将变量发布到 php 脚本并在不刷新页面的情况下获取结果时遇到问题。PHP脚本koord.php
已经过测试,工作正常。
这是我的js代码(adresa
,mjest
o和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]['geometry']['location']['lng']);
}
echo getCoordinates($puna_adresa);
完整的源代码在这里: http://pastebin.com/u/bradetic
谢谢!
Jquery POST 不是问题所在。
您正在执行$.post(...)
这意味着您需要通过$_POST
获取koord.php
参数,并且您正在使用$_GET
,您看到问题了吗?
溶液
将$_GET['puna_adresa'];
更改为$_POST['puna_adresa'];
或
更改客户端中$.get(...)
的$.post(...)
。
你知道POST
和GET
之间的区别吧?
- 你什么时候使用POST,什么时候使用GET?
- 我应该如何在HTML表单中的GET和POST方法之间进行选择?
你真的需要使用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);
你能试试这个吗,
$.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/
你可以试试这个
$.post( "koord.php", $( "#testform" ).serialize() );