我试图从data元素上的htmlspan属性发送数据,并使用Ajax接收数据,然后使用php和mysql进行处理,并在html中将新值返回给我的data属性,但是我得到了一个错误,上面写着“$.parseJSON unexpected character”,有人能看看我的代码,看看我是否在正确处理数据,因为我是新来使用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 {

    }

最佳答案

您不需要使用$.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);
    });

});

你以后也不需要把它串起来。

关于javascript - $ .parseJSON意外字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15709440/

10-11 02:10