返回的数据是不是在jQuery中使用Ajax工作数据、工作、jQuery、Ajax

2023-09-10 19:05:25 作者:月泱白笙箫萦耳

我已经开发了code使用Ajax和jQuery。我已得到my.php的回应,我有 试图以提取响应的值。在这里,code(HTML):

I have developed code with Ajax and jQuery. I have got a response from my.php, and I have tried to extract the values of the response. Here the code (HTML):

?php
    echo '<div id="title">My Title </div>';
    echo '<div id="message"> My message </div>';
?>

我尝试提取标题和邮件,所以我的code是如下。

I try to extract the title and message so my code is below.

    <head>
        <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert("OK");

                $.ajax({
                    type:"POST",
                    url: "my.php",
                    cache:false ,
                    success: function(data){
                        $("#response").html(data);
                        var $response = $(data);
                        var oneval = $response.find('#title').text();
                        var subval = $response.find('#message').text();
                        alert(oneval);
                    }
                });
            });
        </script>
    </head>

    <body>
        <div id="response">
        </div>
    </body>
</html>

...

现在的问题是,当我试图提醒,这是行不通的。有什么不对这个逻辑?我应该使用其他功能来提取标题和消息?

The problem is when I tried to alert, it is not working. What is wrong with this logic? Should I use another function to extract the title and message?

推荐答案

OK,去 http://jsbin.com / udige / ,你可以看到它的工作。

OK, go to http://jsbin.com/udige/ and you can see it working.

关键是使用 .filter ,不.find作为两个div都在响应根元素。我的错误。

The key is using .filter, not .find as the two divs are root elements in the response. My mistake.

基本上做到以下几点:

success: function(data){
    $("#response").html(data);
    var $response = $(data);
    var oneval = $response.filter('#title').text();
    var subval = $response.filter('#message').text();
    alert(oneval);
}