jQuery .load(), 我不想将响应绑定到选择器



我正在使用下面的代码,但我不想在页面中存在#my_id元素,我只想运行.load(),就像这个$.load(

        $("#my_id").load('/code.php', {'code': code}, function(response, status, xhr){
        if(response == "test"){
            $(this).after(' <img src="/accepted.png" alt="accepted" title="accepted"/>');
        }else{
            $(this).after(' <img src="/not_accepted.png" alt="not accepted" title="not accepted"/>');
            //alert("You typed the following: " + voucher_code);
        }

有什么想法吗?谢谢

你想要这样的东西吗?

$.post('/code.php', { code: code }, function(response, status, xhr) {
   ...
});

必须将元素添加到DOM中才能调度加载事件。您还使用.fafter()添加了一些html代码,如果在DOM中添加了$(this),则会起作用。

我建议您将元素添加到DOM中,将其位置设置在可见区域之外的某个位置,然后运行代码。它应该起作用。

这是来自装载()手册:

示例:当页面完全加载时运行一个函数,包括图形

$(window).load(function () {   
    // run code 
});

更新

以下是完整的工作代码(这只是一个例子,应该考虑服务器和客户端的正确验证):

<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
<script>
$(document).load('code.php', {'code': "bla"}, function(response, status, xhr){
        if(response == "test"){
            $('#d').after(' <span>'+response+'</span>');
        }else{
            $('#d').after(' <span>no</span>');
            //alert("You typed the following: " + voucher_code);
        }
});
</script>
<div id="d"> </div>
</body>
</html>

code.php:

$e = $_REQUEST['code'];
if($e) {
echo 'test';
}

输出:

<body>
<script>
...
</script>
<div id="d"> </div> <span>test</span>
</body>

最新更新