$ .parseJSON意外字符

时间:2013-03-29 18:41:56

标签: javascript php jquery mysql ajax

我正在尝试从data元素上的html span属性发送数据并使用Ajax接收它,然后使用php和mysql处理它并将新值返回到我的数据属性中html,但我收到一条错误,上面写着“$ .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 / Ajax

$("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 {

    }

1 个答案:

答案 0 :(得分: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);
    });

});

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