1

我没有做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;
        }
    }
4

1 回答 1

2

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

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

据我记得,只有在以老式方式附加处理程序时返回 false 才有效,在 jQuery 中,您必须显式抑制由表单提交触发的事件的默认操作。

于 2013-05-22T06:52:46.013 回答