0

我正在使用 ajax 进行小型表单验证。用户提供一个密钥,当提交表单时,我调用一个 ajax 方法 validate_key。

我的功能是

function validate_key(){
    $key = $_POST['key'];
    $id = $this->uri->segment(3);
    $query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
    $row = $query->row();
    $download_key = strtolower($row->downloadkey);
    if($download_key == $key){
        return true;
    }
    else{
        return false;
    }
}

jQuery 是

$(document).ready(function() {
    $('#submit').click(function() {
        var key = $('#downloadkey').val();
        var dataString = {KEY:key};
        $.ajax({
            url: "/index.php/home/validate_key",
            type: 'POST',
            data: dataString,
            success: function(msg) {
            }
        });
        return false;
    });
});

形式如下

<form name="form" method="post"> 
   <input id="downloadkey" name="downloadkey" type="text" />
   <input type="submit" id="submit" name="submit" value="submit"/>
</form>

我检查用户向数据库提供的密钥是否正确允许用户查看页面并在会话中设置密钥如果错误则给出警报消息并再次呈现表单

如何检查响应?

谢谢

4

2 回答 2

3

我想你需要从你的 PHP 页面回显

if($download_key == $key){
        echo "true";
    }
    else{
        echo "false";
    }

然后在您的 Ajax 成功处理程序中,您可以检查回调中的响应。确保您还通过调用该 preventDefault()函数来阻止默认操作,以便页面不会被发布。

$(document).ready(function() {
    $('#submit').click(function(e) {
       e.preventDefault();
        var key = $('#downloadkey').val();
        var dataString = {KEY:key};
        $.ajax({
            url: "/index.php/home/validate_key",
            type: 'POST',
            data: dataString,
            success: function(msg) {
                  if(msg=="true") 
                    {
                       alert("do something")
                    }
                    else
                    {
                       alert("do something else")
                    }                        

            }
        });           
    });
});
于 2012-08-06T13:57:07.400 回答
0

You need to output something to the page. If you just return true or return false nothing will get output.

So do something like:

echo "OK"

and then you can do this in your javascript:

if(msg == "OK"){ .. }

The other thing you can do is return a HTTP status code e.g.

header("HTTP/1.1 200 OK");

You can check this in your jquery. Using the first method however is more useful because you can have any number of outputs on the page, including different error messages and such.

于 2012-08-06T13:58:26.290 回答