简体   繁体   中英

Jquery + Append + PHP

My code (index.html)

<script>
    $(document).ready(function() {
        var interval = setInterval(function() {
            $.get("load_txt.php", { 'var1': 4, 'var2' : 52},
                function(data){ $('#msg').append(data); }, "json");
            });
        }, 1000);
    });
</script>
<p id='msg'></p>

My code (load_txt.php)

<?php
$var1 = $_GET['var1'];
$var2 = $_GET['var2'];

    $data = "var1= " . $var1 . " " . "var2= " . $var2;

    echo json_encode($data);
?>

It doesnt work, nothing is showing in #msg. Can you see some mistake? if yes, please answere, thx :)

You're not actually returning JSON. You're running a string through json_encode with no key, which is just giving you back a string. This is then returned to jQuery which is expecting JSON so is most likely throwing an error trying to deserialise a plain string.

To fix this, change your PHP code to actually return JSON:

echo json_encode(array('var1' => $var1, 'var2' => $var2));

And amend your jQuery to read from the deserialised object:

var interval = setInterval(function() {
    $.get("load_txt.php", { 
        'var1': 4, 
        'var2': 52
    }, function(data) { 
        $('#msg').append(data.var1 + ' ' + data.var2); 
    }, "json");
}, 1000);

Also note that making AJAX requests using setInterval is not a great idea, as if the requests take longer than the interval to complete they will stack up. It's better to use setTimeout and make the new request when the previous one has completed:

function makeRequest() {
    $.get("load_txt.php", { 
        'var1': 4, 
        'var2': 52
    }, function(data) { 
        $('#msg').append(data.var1 + ' ' + data.var2); 
        setTimeout(makeRequest, 1000); // on success
    }, "json");
}
makeRequest(); // on load

It's just a syntax error:

This code works ok:

$(document).ready(function() {
    var interval = setInterval(function() {
        $.get("load_txt.php", { 'var1': 4, 'var2' : 52},
            function(data){ $('#msg').append(data); }, "json");
    }, 1000);
});

; Note, this(**) piece need to be deleted:

$(document).ready(function() {
    var interval = setInterval(function() {
        $.get("load_txt.php", { 'var1': 4, 'var2' : 52},
            function(data){ $('#msg').append(data); }, "json");
        **});**
    }, 1000);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM