用一个ajax函数更改两个html id

时间:2013-02-21 21:36:18

标签: php javascript html ajax json

我需要在我的ajax请求中添加一些内容,以显示它从<span id="total_vote_down_<?php echo $mes_id2; ?>">减去1现在我的ajax只是将<span id="total_vote_up_<?php echo $mes_id1; ?>">的值加1,我需要从{{1}中减去1在同一个函数中。我知道我的代码很邋.... ......跟我一起承受......

顺便说一下,我知道ajax实际上并没有添加和减去任何东西,它只是为客户端展示它,只是不知道更好的方式来表达我的问题

general.js

<span id="total_vote_up_<?php echo $mes_id1; ?>">

的index.php

$(".vote").click(function() 
{

var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);


if(name=='up')
{

$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,

success: function(data) { $('#total_' + parent.attr("id")).text(data); }
});

}
else
{

$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,

success: function(data) { $('#total_' + parent.attr("id")).text(data); }

});


}

});

这里是up.php

<div id="main">
<div id="left">
<span class='up'><a title="vote_down_" id="vote_up_<?php echo $mes_id1; ?>" class="vote" name="up" data-options="key1=<?php echo $mes_id1;?>&key2=<?php echo $mes_id2;?>&key3=<?php echo $totalvotes1;?>&key4=<?php echo $totalvotes2;?>"> <img src="up.png" alt="Down" /></a></span><br />
<span id="total_vote_up_<?php echo $mes_id1; ?>"><?php echo $totalvotes1; ?></span><br />
</div>
<div id="message">
    <?php echo $message1; ?>
</div>
<div class="clearfix"></div>
</div>
<div id="main">
<div id="right">
<br />
<span id="total_vote_down_<?php echo $mes_id2; ?>"><?php echo $totalvotes2; ?></span><br />
<span class='down'><a id="vote_down_<?php echo $mes_id2; ?>" class="vote" name="down" data-options="key1=<?php echo $mes_id1;?>&key2=<?php echo $mes_id2;?>"><img src="down.png" alt="Down" /></a></span>
</div>
<div id="message">
    <?php echo $message2; ?>
</div>
<div class="clearfix"></div>
</div>

down.php与相反的值相同

1 个答案:

答案 0 :(得分:1)

如果在PHP中创建关联数组,则可以使用json_encode将其转换为JSON。像这样:

// obviously this will be constructed dynamically from your database
$d = array('Will' => 10, 'Henry' => 12);
// echo as json
echo json_encode($d);

然后在你的JavaScript中:

$.ajax({
    type: "POST",
    url: "down.php",
    data: dataString,
    cache: false,
    dataType: "json",

    success: function(data) { 
        // here data will look like { "Will":10, "Henry": 20 };
        // I'm going to assume `total_will` is the total votes for william
        var candidate;
        for (candidate in data) {
            $("#total_" + candidate).text(data[candidate]);
        }
        // now #total_Will has the text 10
        // and #total_Henry has the text 20
    }
});