使用ajax显示正在选择的内容不起作用,PHP,AJAX,JAVASCRIPT

时间:2015-06-16 02:15:14

标签: javascript php jquery ajax

使用ajax,我正在尝试显示正在选择的内容,但由于某种原因它根本没有显示任何内容。我知道ajax函数本身是通过在函数内使用alert来调用的,我认为真正的问题实际上是在test2.php中,但我不确定我做错了什么。请看一下:

  

test1.php

<?php

include('ajax.php');

echo "<select name = 'select' onchange = 'ajax(\"test2.php\",\"output\")'>";

echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "<option value = '3'> 3 </option>";

echo "</select>";
echo "<div id = 'output'/>";

?>
  

TEST2

<?php

$select = $_POST['select'];
echo $select;

?>
  

ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajax(url,id) {

      $.ajax({
           type: "POST",
           url: url,
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( id ).innerHTML = data;
           }

      });

}

</script>

2 个答案:

答案 0 :(得分:1)

您尚未将数据发布到test2 !!

<?php

include('ajax.php');

echo "<select id = 'select' onchange = 'ajax(\"test2.php\",\"output\")'>";

echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "<option value = '3'> 3 </option>";

echo "</select>";
echo "<div id = 'output'/>";

?>

function ajax(url,id) {

      $.ajax({
           type: "POST",
           url: url,
           data : {select:$('#select').find("option:selected").val()}, 
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( id ).innerHTML = data;
           }

      });

}

答案 1 :(得分:0)

您在Ajax请求中缺少数据属性。

将PHP脚本和HTML混合在一起是一种不好的做法。始终考虑分离关注点。

这是你应该怎么做的。

<?php 
include('ajax.php');
?>
<select name = 'select'>"
    <option value = '1'> 1 </option>
    <option value = '2'> 2 </option>
    <option value = '3'> 3 </option>
</select>
<div id = 'output'/>

Ajax.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 
$(function () {
    $(document).on('change','select',function () {
        var data = $(this).val();
        $.ajax({
           type: "POST",
           url: "test2.php",
           data: data,
           error: function(xhr,status,error){alert(error);},
           success:function(response) {
               $("#output").html(response);
           }

        });
    });

});
</script>