【问题标题】:Trying to work with AJAX & PHP尝试使用 AJAX 和 PHP
【发布时间】:2013-05-22 06:45:10
【问题描述】:

我与AJAX 的合作不多,但我一直在尝试做的是有一个用户输入数据的表单,单击提交,而不是刷新页面以获取结果,modal window 打开结果。我的理解是,我需要使用AJAX 才能工作。

以下是我到目前为止的代码。请注意,我只是想让AJAX 调用首先工作,稍后我会担心模式窗口。

目前,点击提交按钮时所实现的只是页面执行表单操作并转到testauthcall.php,我的结果是空白页面上的echo'd(我认为return false;应该杀死页面加载?)。

HTML 文件:testauth.php

<form id="myForm" action="testauthcall.php" method="post"> 
    Username: <input type="text" name="user" /> 
    Password: <input type="text" name="pass" />
    <input type="submit" value="Test Authentication" /> 
</form>

Javascript 文件:testauth.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

<script type="text/javascript"> 

var frm = $('#myForm');
frm.submit(function () {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            alert('ok');
        }
    });
    return false;
});

<script>

PHP 文件:testauthcall.php

require_once('variables/radius.class.php');

    if ((isset($_POST['user'])) && ('' != trim($_POST['user'])))
    {
        $radius = new Radius('xxx.xxx.xxx.xx', 'xxxxxxxxxx');

        if ($radius->AccessRequest($_POST['user'], $_POST['pass']))
        {
            $authresult = "<strong>Authentication accepted.</strong>";
            echo $authresult;
        }
        else
        {
            $authresult = "<strong>Authentication rejected.</strong>";
            echo $authresult;
        }
    }

【问题讨论】:

    标签: javascript php html ajax


    【解决方案1】:

    所以你的问题是页面正在重新加载,即使它不应该重新加载?我假设你正在使用 jQuery?尝试像这样编写表单提交处理程序:

    frm.submit(function (e) {
        if (e) {e.preventDefault()};
        //...
    });
    

    据我所知,只有在以老式方式附加处理程序时返回 false 才有效,在 jQuery 中,您必须明确禁止表单提交触发的事件的默认操作。

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2017-06-23
      相关资源
      最近更新 更多