【问题标题】:Prevent Page from complete refresh while passing data from ajax从ajax传递数据时防止页面完全刷新
【发布时间】:2018-05-03 06:58:50
【问题描述】:

我正在尝试在头 php 文件上提交简单的表单并访问它的值以在我的一个视图中更改页面的内容。我能够传递 ajax 值,但是当我这样做时,完整的标题页面会再次重新加载。请帮助我如何防止页面重新加载。

这是我在头文件中的表单

<form  class="choose-form form-holder" >
                                <select id="usertype" onChange="selectChange()">
                                    <option value=1>JS</option>
                                    <option value=2>JP</option>
                                </select>
</form>

这是我在 php 头文件中提交表单的脚本

<script>
function selectChange() {
            debugger;
            var usertype = $('#usertype').val();
                $.ajax({
                    type: 'GET',
                    data: {usertype: usertype},
                    success: function (response) {                  
                        $('#response').html(response);
                    },
                    error: function () {
                        alert("error");
                    }
                });
                return false;
        }
</script>

这是我在 php 视图页面中访问类型和更改内容的代码

<div id="response">
        <?php if(!empty($_GET['usertype'])){
            $type = $_GET['usertype'];

        }
?></div>

<?php if ((isset($type)) && ($type == 2)){?>
            //some other content
<?php }else{  ?>
    //change the content
<?php } ?>

【问题讨论】:

  • 你的 AJAX 指向哪里?我没有看到任何目标文件。
  • 我没有传递url,因为我想在同一页面上获取数据
  • 那么您在这里所做的是在选择时检查他们选择的内容并基于此显示适当的内容?那么你就不需要ajax了,因为这一切都可以使用JS来完成
  • 好的,非常感谢您的建议!你能帮我如何通过 JS 并检查我的 if else 条件吗?很抱歉,我对此很陌生,并且正在学习它。
  • 请添加“jquery”标签。

标签: javascript php ajax


【解决方案1】:

试试下面:

<script>
function selectChange(event) {
    event.preventDefault();
    debugger;
    var usertype = $('#usertype').val();
    $.ajax({
        type: 'GET',
        data: {usertype: usertype},
        success: function (response) {
            $('#response').html(response);
        },
        error: function () {
            alert("error");
        }
    });
    return false;
}

【讨论】:

  • 感谢 Sibusiso。我试过这个。它给了我“未捕获的类型错误:无法读取未定义的属性'preventDefault'”错误。请问我需要在这里添加更多内容吗?
猜你喜欢
  • 2018-08-12
  • 2017-03-14
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多