javascript - $.parseJSON 意外字符

标签 javascript php jquery mysql ajax

我正在尝试从 span 元素上的 html data 属性发送数据并使用 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 {

    }

最佳答案

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

相关文章:

javascript - 使用 javascript 获取 gridview 文本框值的总和并在标签中显示总计

javascript - '未捕获类型错误 : undefined is not a function' keeps showing up for different lines of code

javascript - 我在哪里放置 NaN 代码?

javascript - jQuery,移动点并获得协调

javascript - 如何在javascript中同时检查if和else if

php - 开箱即用的 Eclipse PDT(PHP 开发工具)不能调试 PHP,为什么?

强制严格键入、分号和验证代码的 Javascript IDE,如 JSLint(或 : that adds the advantages of a compiler to Javascript)?

javascript - 用作委托(delegate)人时传递到 .on 的有效候选人

javascript - 使用Ext.js从WCF获取数据 "Network Error 400 Bad Request"

php - SQL 查询构造