我有一张表格根据用户的邮政编码输入计算运费。我正在检索用户对邮政编码的文本输入,通过PHP检索该特定邮政编码的运输成本,然后使用AJAX调用将其转移回HTML中的输出总计。但是,他的AJAX调用并没有取代HTML。
(相关)HTML:
<input type="text" id="postcode" name="postcode">
<div id="result"></div>
JS:
$(document).ready(function() {
$('#postcode').change(function(){
$.ajax({
type: "GET",
url: "shipping.php",
data: 'shipping=' + $('#postcode').val(),
success: function(msg){
$('#result').html(msg);
}
}); // Ajax Call
});
}); //document.ready
PHP:
<?php
$postcode = (is_numeric($_GET['postcode']) ? (int)$_GET['postcode'] : 0);
if ($postcode >= 2000 && $postcode <= 2234) {
$shipping = 55.00;
} elseif ($postcode >= 2250 && $postcode <= 2310) {
$shipping = 105.00;
}
echo $shipping;
?>
答案 0 :(得分:4)
使用:
$postcode = (is_numeric($_POST['postcode']) ? (int)$_POST['postcode'] : 0);
和
$.ajax{ type: "GET", ... }
您使用 GET 通过查询字符串发送了代码,但您的PHP代码正在尝试从 POST 正文中读取值。
答案 1 :(得分:3)
$postcode = (is_numeric($_GET['postcode']) ? (int)$_GET['postcode'] : 0);
将该行更改为:
$postcode = (is_numeric($_GET['shipping']) ? (int)$_GET['shipping'] : 0);
答案 2 :(得分:2)
你的ajax正在发送GET而你的PHP正在读取$ _POST,试试这个:
<?php
$postcode = (is_numeric($_GET['postcode']) ? (int)$_GET['postcode'] : 0);
if ($postcode >= 2000 && $postcode <= 2234) {
$shipping = 55.00;
} elseif ($postcode >= 2250 && $postcode <= 2310) {
$shipping = 105.00;
}
echo $shipping;
?>