在html中显示JQuery变量

时间:2014-03-15 15:06:15

标签: html ajax

这是my_js.js

$(document).ready(function () {
    $.getJSON("fetch.php", function (data) {
        $("ul").empty();
        $.each(data.result, function () {
            var name = this['sender_name'];
            var age = this['sender_age'];
            var photo = this['sender_photo'];
            var language = this['sender_language'];
            var country = this['sender_country'];
            var message = this['message'];
            $('div.haha').html('<p>This is the message ' + message 
                + ' my name is ' + name + ' my age ' + age + ' my language ' 
                + language + ' my country ' + country + '</p>');
        });
    });
}

和html代码是

<html>
    <body>
        <ul></ul>
        <div class="haha"></div>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="my_js.js"></script>
    </body>
</html>

所有这些变量都无法在html div中显示,所有变量都是从fetch.PHP成功加载的。

3 个答案:

答案 0 :(得分:0)

您的成功函数应该是一个单独的参数:

$.getJSON("fetch.php", function (data) {
    $("ul").empty();
    $.each(data.result, function () {
        var name = this['sender_name'];
        var age = this['sender_age'];
        var photo = this['sender_photo'];
        var language = this['sender_language'];
        var country = this['sender_country'];
        var message = this['message'];
    });

    $('div.haha').html('<p>This is the message ' + message + ' my name is ' 
        + name + ' my age ' + age + ' my language ' + language + ' my country ' 
        + country + '</p>');
});

http://api.jquery.com/jquery.getjson/

答案 1 :(得分:0)

将您提取的src放在var

    var photolink = photo <!---- This is what you extracted from the database --->

   <!----- This will place to that img with class asd the src atributre from the var ----> 
        photolink =   $('.asd').attr('src');

        <div>
           <img class="asd" src="">
        </div>

可能会工作!!

答案 2 :(得分:0)

尝试使用text()方法代替html()方法,

$(document).ready(function () {
    $.getJSON("fetch.php", function (data) {
        $("ul").empty();
        $.each(data.result, function () {
            var name = this['sender_name'];
            var age = this['sender_age'];
            var photo = this['sender_photo'];
            var language = this['sender_language'];
            var country = this['sender_country'];
            var message = this['message'];

            $('div.haha').text('This is the message ' + message 
             + ' my name is ' + name + ' my age ' + age + ' my language ' 
             + language + ' my country ' + country);
        });
    });
});