1

我需要一个更好的解决方案然后这个,我<span id="<?php echo $row['art_id']" name="<?php echo $row['art_featured']"></span>用来从我的数据库中获取字段的值,所以我可以通过 jQuery Ajax 发送它们,但是必须有更好的方法来使用我的数据库中的值并将它们存储在一个jQuery VAR 然后这个,任何建议都会非常感谢提前!

jQuery

        $(document).ready(function(){

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

        var art_id = $(this).attr('id');
        var art_featured = $(this).attr('name');

        $.ajax({
        type: "POST",
        data: {art_id:art_id,art_featured:art_featured},
        url: "ajax-feature.php",
        success: function(data){
            if(data != false) {

            } 
            else {

            }  
        }
        });

    });

});

PHP

    <section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"; 

    if($result = query($sql_categories)){
        $list = array();

        while($data = mysqli_fetch_assoc($result)){
            array_push($list, $data);
        }

        foreach($list as $i => $row){ 
        ?>
            <div class="row">
                <div class="column one">
                     <span id="<?php echo $row['art_id']; ?>" class="icon-small star"></span>
                </div>
            </div>
        <?php
        }
    }
    else {
        echo "FAIL";
    }
?>
</section>

那么我可以将数据对象与 ajax 一起使用data:吗?

4

1 回答 1

1

我更喜欢使用这样的东西:

<span 
     data-object='{"art_id":<?=$row['art_id']?>,
                  "art_featured":"<?=$row['art_featured']?>"}'
     onclick="ajaxFunction($(this))"
>
</span>

function ajaxFunction(o){
      var data = o.data('object');
      /* you can send:
       * data.art_id
       * data.art_featured
       */
}

http://jsfiddle.net/M4AFQ/1/

后续问题的更新:

$(".star").click(function(){
      var data = $(this).data('object');
      /* you can send:
       * data.art_id
       * data.art_featured
       */
  });
于 2013-03-26T02:13:47.190 回答