AJAX调用不替换HTML

时间:2013-09-29 12:09:32

标签: javascript php ajax forms

我有一张表格根据用户的邮政编码输入计算运费。我正在检索用户对邮政编码的文本输入,通过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;
?>
  • 如果我在控制台中键入msg,则返回undefined。它不应该有一个值(邮政编码输入确实属于正确的条件)..?

3 个答案:

答案 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;
?>