【问题标题】:Ajax post value and store in php variableAjax 发布值并存储在 php 变量中
【发布时间】:2014-02-24 03:20:55
【问题描述】:

我这里有一个 ajax。我需要知道是否可以根据 onchange 事件发回 post 值并将其存储在主页的 php 变量中? $_POST["mainlist_id"] 存储在 php var 中?

getajax.php

<?php
if (isset($_POST["mainlist_id"])) {
    $mysqli = new mysqli("localhost", "root", "", "2015");
    $main = $mysqli->real_escape_string($_POST["mainlist_id"]);


$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");

    $option1 = '';
     while($row = $result1->fetch_assoc())
        {
        $option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
        }
        echo $option1;
    }
?>

主页

<script type="text/javascript">
    $('#main').change(function () {
        $.ajax({
            url: 'getajax.php',
            data: {
                mainlist_id: $(this).val()
            },
            dataType: 'html',
            type: 'POST',
            success: function (data) {
                $('#languages').html(data);
            }
        });
    });
</script>

【问题讨论】:

  • 为什么你想把你的 POST 数据从它来的地方再次发回“主页”?因为,您已经在“主页”中拥有该数据。
  • 您可以在 getajax.php 页面中使用$_SESSION 来存储 POST 变量并在主页中访问它。

标签: php jquery ajax


【解决方案1】:

getajax.php

<?php
session_start();
if (isset($_POST["mainlist_id"])) {
    $mysqli = new mysqli("localhost", "root", "", "2015");
    $main = $mysqli->real_escape_string($_POST["mainlist_id"]);
    $_SESSION['mainlist_id']=$main; 

$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");

    $option1 = '';
     while($row = $result1->fetch_assoc())
        {
        $option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
        }
        echo $option1;
    }
?>

主页

<?php session_start();
    $main_id=$_SESSION['mainlist_id'];
    ?>
    <script type="text/javascript">
        $('#main').change(function () {
            $.ajax({
                url: 'getajax.php',
                data: {
                    mainlist_id: $(this).val()
                },
                dataType: 'html',
                type: 'POST',
                success: function (data) {
                    $('#languages').html(data);
                }
            });
        });
    </script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多