简体   繁体   中英

Why is AJAX only replacing my variable in some places?

I have the following AJAX code, which replaces anything with class "percentreplacer" with the data in the "Percent" column of the MYSQL database:

<script type='text/javascript'>
$(document).ready(function () {
    $('#functionsquestionform2').on('submit', function(e) {
        e.preventDefault();
        $.ajax({  
            url :  "aplaygroundajaxtest.php",
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
$(".percentreplace").text(data.percent); 
            },
            });
        });
});
</script>

In another part of my script, I have this snippet of PHP code:

 <?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>

When I run the code, the AJAX code at the top successfully replaces the above span with the percent value stored in the database (such as "6").

Later on in my code, I try to set this percent as a variable with the JQuery script shown below:

<script type='text/javascript'>
$(function(){    
var carouselbutton1percentage='<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>' ....[cont'd]

Here, however, instead of replacing the entire PHP snippet with the percent (let's say 6), it sets the variable carouselbutton1percentage equal to <span class="percentreplace">6</span> I want the tags to get stripped here just like they did in the former. I'm guessing this has something to do with the quotes, but I've played around with it quite a bit and I can't figure out what to change.

Any help would be greatly appreciated!

Thanks

I might be missing something. But instead of storing a string 'that contains characters that look like PHP and jquery', I would think you want to actually update that html element, like you do in the AJAX response block. So..

$(".percentreplace").text('6');

or

var carouselbutton1percentage = 6;

$(".percentreplace").text(carouselbutton1percentage);

But again, maybe I'm misunderstanding.

我认为您需要适当地转义字符串吗?

var carouselbutton1percentage='<?php echo \'<span class="percentreplace">\'.$data[\'FunctionsPercent\'].\'</span>\'‌​; ?>';

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