Ajax从php

时间:2016-04-15 08:53:04

标签: php ajax

的Ajax

$(document).ready(function(){
          $("#diklat").change(function(){
            var diklat = $("#diklat").val();
            $.ajax({
                url: "function.php",
                data: {'action': 'diklat'},
                cache: false,
                success: function(msg){
                    $("#angkatan").html(msg);
                }
            });
          });

PHP

    $get_action = $_GET['action'];
if($get_action=='diklat'){
        $diklat = $_GET['diklat'];
        $angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
        echo "<option>-- Pilih Angkatan --</option>";
        while($p = mysql_fetch_array($angkatan)){
            echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
        }
    }

该值不包含在我的ajax中,ajax只读取echo。如何获得该值

3 个答案:

答案 0 :(得分:0)

你写过data: {'action': 'diklat'}但它应该是dilkat,不带引号作为变量,所以在php中你会得到$_GET['action']的价值。

<强>的Ajax

$(document).ready(function(){
          $("#diklat").change(function(){
            var diklat = $("#diklat").val();
            $.ajax({
                url: "function.php",
                data: {'action': diklat},
                cache: false,
                success: function(msg){
                    $("#angkatan").html(msg);
                }
            });
          });

<强> PHP

if($_GET['action'] == 'diklat'){
    $diklat = $_GET['action'];
    $angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
    echo "<option>-- Pilih Angkatan --</option>";
    while($p = mysql_fetch_array($angkatan)){
        echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
    }
}

答案 1 :(得分:0)

两件事:

对于GET请求,要求PHP服务器,数据应该是URL编码的(如您所见here,查询字符串只是附加到URL ...)所以告诉{{1 } ...

编辑:Jquery自动将对象转换为Url编码的查询字符串...所以它适用于数组!我和angular的$ http混淆了......

而且,参数将在'data' : '?action=diklat'中(因为操作是参数名称,并且 ...所以PHP将查询字符串转换为关联数组,参数名称为keysn,值为值...

答案 2 :(得分:0)

你应该传递2个变量,一个动作和另一个id(diklat)

<强>的Ajax:

$(document).ready(function(){
          $("#diklat").on('change', function(){
            var diklat = $("#diklat").val();
            $.ajax({
                type: "POST",
                url: "function.php",
                data: {'action': 'diklat', 'diklat':diklat},
                cache: false,
                success: function(msg){
                    $("#angkatan").html(msg);
                }
            });
          });

<强> PHP

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action == 'diklat')
{
    $diklat   = isset($_POST['diklat']) ? $_POST['diklat'] : '';
    $angkatan = mysql_query("SELECT id, name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
    echo "<option>-- Pilih Angkatan --</option>";
    while($p = mysql_fetch_array($angkatan))
    {
        echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
    }
}