gpt4 book ai didi

javascript - $.parseJSON 意外字符

转载 作者:行者123 更新时间:2023-11-29 05:30:09 25 4
gpt4 key购买 nike

我正在尝试从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com