AJAX POST和PHP POST在同一页面

时间:2019-03-03 12:22:42

标签: php jquery ajax

我有2个下拉列表,分别为drpcategorydrpitem,如下所示;

<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);

foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div> 

<div class="form-group">
<label>Item</label>
<select class="form-control bg-dark btn-dark text-white" id="drpitem" name="drpitem">
<?php
$category = $_POST["drpcategory"] ?? 'Electronics';
$item = ''.$dir.'/template/post/'.$category.'/item.txt';
$item = file($item, FILE_IGNORE_NEW_LINES);

foreach($item as $item)
{
echo "<option value='".$item."'>$item</option>";
}
?>
</select>
</div>

如您所见,根据drpcategory的选定值,drpitem应该被动态填充。

如果您想知道,如果我没有进行任何$category检查的情况下手动设置post,两个下拉列表都将经过PHP循环并填充。

现在,我正在使用AJAX postdrpcategory中的更改发布到下面的同一页面中;

<script>
  $(function(){

    $('#drpcategory').on('change',function()
    {

      $.ajax({
        method: 'post',
        data: $(this).serialize(),
        success: function(data)
        {
          alert(data);
        }
      });

    });    

  });
</script>

以下是上述AJAX post Chrome 浏览器> 检查> 网络标签输出;

Inspect

是的,我正在post将此AJAX放入同一页面,并且url是:http://example.com/?page=post,与此“网络”标签显示的相同。

我已从AJAX函数中删除了url字段,因为浏览器会自动选择当前页面,因此效果更好,不,手动在其中写入任何url不会改变我的内容在下面要问。

问题是,如何使drpitem成为AJAX post ed drpcategory值并开始动态填充?

我想AJAX post到同一页面,所有这些都应该在不重新加载页面的情况下发生。

2 个答案:

答案 0 :(得分:0)

您得到所有​​html元素的返回吗? 如果发帖请求发生,请在您的php函数中添加“如果条件”,则返回php结果,否则返回html元素。 您的网址中的“ /?page = post”是什么?请var_dump($ _ POST,$ _ GET);在ajax请求功能中,请给我答复。 否则,您可以将此请求发送到新创建的功能以进行测试建议吗?

答案 1 :(得分:0)

最后,在等待7天以上才能弄清楚这一点之后,我无法AJAX post到同一页面,可能是因为同一页面中已经有太多<html>元素。但这里使用外部post.php文件。除了上面我最初的问题中提到的内容以外,我仅需要进行这些更改即可。

<script>
$(function()
{
$('#drpcategory').change(function()
{
$.ajax({
method: 'post',
url: 'post.php',
data: $(this).serialize(),
success: function(data)
{
$('#drpitem').html(data);
}
});
});
});
</script>

然后,我不得不将此post.php保存在index.php所在的根网站目录中。根据需要更改目录,并且还记得更改上述AJAX函数中的url字段。

<?php include 'config.php';?> //this is where the $dir variable is derived in my website. i had to include this since post.php is an external file that doesn't know about the variable.

<?php
$category = $_POST["drpcategory"];
$item = ''.$dir.'/template/post/'.$category.'/item.txt';
$item = file($item, FILE_IGNORE_NEW_LINES);

foreach($item as $item)
{
echo "<option value='".$item."'>$item</option>";
}
?>

感谢大家,并带领我逐步完成。如果给出直接答案,我会标记您中的某个人为答案,但是如果有人已经给出了答案,对不起您未能正确理解您。但我认为最终目标是让某人以此作为帮助。