1

我正在尝试从元素data上的 html 属性发送数据span并使用 Ajax 接收它,然后使用 php 和 mysql 处理它并将新值返回给我在 html 中的 data 属性,但是我收到一个错误,上面写着“$ .parseJSON 意外字符”,有人可以查看我的代码,看看我是否正确处理数据,因为我是使用 JSON 的新手。

HTML / PHP

<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}' 
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->

jQuery/阿贾克斯

$("span[class*='star']").on('click', function () {
    var data = $.parseJSON($(this).data('object'));
    var $this = $(this);

    $.ajax({
        type: "POST",
        url : "ajax-feature.php",
        data: {art_id: data.art_id,art_featured: data.art_featured}
    }).done(function(result) {
        data.art_featured = result;
        $this.data('object', JSON.stringify( data ));
    });

});

PHP/mySQL

if($_POST['art_featured']==1) {
        $sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];

        $result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
        echo json_encode($result);
    }
    else if($_POST['art_featured']==0){
        $sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];

        $result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
        echo json_encode($result);
    }

    if(query($sql_articles)) {

    }
    else {

    }
4

1 回答 1

3

你不需要使用$.parseJSON,jQuery 会为你做这些。

$("span[class*='star']").on('click', function () {
    var data = $(this).data('object');
    var $this = $(this);

    $.ajax({
        type: "POST",
        url : "ajax-feature.php",
        data: {art_id: data.art_id,art_featured: data.art_featured}
    }).done(function(result) {
        data.art_featured = result;
        $this.data('object', data);
    });

});

您也不需要稍后对其进行字符串化。

于 2013-03-29T18:44:04.647 回答