gpt4 book ai didi

php - JSON 单项

转载 作者:行者123 更新时间:2023-11-30 22:46:17 26 4
gpt4 key购买 nike

我正在创建一个项目来使用评级系统评估不同的产品,但由于我是新手,所以我有几个问题。

首先,为了实现这个目标,我创建了一个 ListView ,它允许我使用从该数据库获取的 JSON 代码显示 MySQL 数据库中记录中的信息。

现在的项目是这样的http://jsfiddle.net/c52m6smg/1/ .我的问题如下,我可以通过 AJAX 调用替换 var 信息以从外部文件或本地主机上存储的 php 文件检索 JSON 数据吗?

另一方面,在这个基础上,我可以访问每条记录的信息,但我可以在显示中放置一个评级系统来精确影响显示的寄存器?或者我应该做不同的事情?我一直在搜索,我看到一个可能的选项是创建一个 PHP 文件来检索提供选项的特定记录,例如 localhost/rating/individualjson.php&search=?

对不起,如果有什么愚蠢的问题,但我正在努力学习。我不要求完成项目的代码,只要求提供我提出的问题的信息和答案、可能有帮助的类似案例的建议或示例。

最后,我有以下代码可以从数据库中获取所有数据:

这里是 PHP 文件:

<?php

// Error function that stops script processing with die
function error($message){
$output = json_encode(
array(
'result' => 'error',
'msg' => $message
)
);
die($output);
}

// Round to the nearest 0.5
function roundToNearestHalf($number){
return round($number * 2) / 2;
}

// Instantiate database connection
$db = new mysqli('localhost', 'root', 'XXX', 'XXX');

// Check that the connection worked
if($db->connect_errno > 0){
error('Unable to connect to database [' . $db->connect_error . ']');
}

// Verify that we have enough post items
if(count($_POST) > 1){
error('Too many post items received.');
}

// Check that the rating was entered
if(!isset($_POST['rating']) || $_POST['rating'] == ''){
error('No rating value provided.');
}

// Valid the rating amount that was entered.
if(!preg_match("/[0-5](?:\.5)/", $_POST['rating']) && $_POST['rating'] < 0 && $_POST['rating'] > 5){
error('Invalid rating provided.');
}

// Check if the user has rated before
$sql = <<<SQL
SELECT `ratingid`
FROM `ratings`
WHERE `ip` = '{$_SERVER['REMOTE_ADDR']}'
SQL;

if(!$result = $db->query($sql)){
error('There was an error running the query [' . $db->error . ']');
}

// Tell the user that they have voted already.
if($result->num_rows){
error('That IP address has already voted, please try using another IP.');
}

// Store the user's rating.
$rating = $db->escape_string($_POST['rating']);

$sql = <<<SQL
INSERT INTO `ratings`
(`rating`, `ip`)
VALUES ('{$rating}', '{$_SERVER['REMOTE_ADDR']}')
SQL;

if(!$db->query($sql)){
error('Unable to insert rating to database [' . $db->error . ']');
}

// Get the average rating
$sql = <<<SQL
SELECT AVG(`rating`) AS `rating`
FROM `ratings`
SQL;

if(!$result = $db->query($sql)){
error('There was an error running the query [' . $db->error . ']');
}

// Fetch the average rating
$data = $result->fetch_assoc();

$rating = $data['rating'];

// Output the average rating for the front end to handle
$output = json_encode(
array(
'result' => 'success',
'rating' => roundToNearestHalf($rating)
)
);
echo $output;
?>

来自 MySQL 的表:

CREATE TABLE `rating` (
`ratingid` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`rating` FLOAT UNSIGNED NOT NULL,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ip` VARCHAR( 39 ) NOT NULL,
UNIQUE (`ip`)
) ENGINE = INNODB

这里是 js 字段:

var info = [{
"id": "1",
"ISBN": "978487485",
"titol": "20.000 Leguas de viaje Submarino",
"autor": "---",
"any": "1978",
"descripcio": "asdsadasdafsa",
"format": "Book",
"stars": "5"
},
{
"id": "2",
"ISBN": "978848481",
"titol": "Intocable",
"autor": "Philipp",
"any": "1999",
"descripcio": "asdadaf",
"format": "Book",
"stars": "2"
},
{
"id": "3",
"ISBN": "884697989",
"titol": "Baba Ramdev",
"autor": "Patanjali",
"any": "2000",
"descripcio": "Herbal Hand Wash Refill",
"format": "Book",
"stars": "3"
}];


//pageinit event for first page
//triggers only once
//write all your on-load functions and event handlers pertaining to page1
$(document).on("pageinit", "#info-page", function () {


//set up string for adding <li/>
var li = "";
//container for $li to be added
$.each(info, function (i, titol) {
//add the <li> to "li" variable
//note the use of += in the variable
//meaning I'm adding to the existing data. not replacing it.
//store index value in array as id of the <a> tag
li += '<li><a href="#" id="' + i + '" class="info-go">' + titol.titol + '</a></li>';
});
//append list to ul
$("#prof-list").append(li).promise().done(function () {
//wait for append to finish - thats why you use a promise()
//done() will run after append is done
//add the click event for the redirection to happen to #details-page
$(this).on("click", ".info-go", function (e) {
e.preventDefault();
//store the information in the next page's data
$("#details-page").data("info", info[this.id]);
//change the page # to second page.
//Now the URL in the address bar will read index.html#details-page
//where #details-page is the "id" of the second page
//we're gonna redirect to that now using changePage() method
$.mobile.changePage("#details-page");
});

//refresh list to enhance its styling.
$(this).listview("refresh");
});
});

//use pagebeforeshow
//DONT USE PAGEINIT!
//the reason is you want this to happen every single time
//pageinit will happen only once
$(document).on("pagebeforeshow", "#details-page", function () {
//get from data - you put this here when the "a" wa clicked in the previous page
var info = $(this).data("info");
//string to put HTML in
var info_view = "";
//use for..in to iterate through object
for (var key in info) {
//Im using grid layout here.
//use any kind of layout you want.
//key is the key of the property in the object
//if obj = {titol: 'k'}
//key = titol, value = k
info_view += '<div class="ui-grid-a"><div class="ui-block-a"><div class="ui-bar field" style="font-weight : bold; text-align: left;">' + key + '</div></div><div class="ui-block-b"><div class="ui-bar value" style="width : 75%">' + info[key] + '</div></div></div>';
}
info_view += '<span data-id="'+info['id']+'" class="stars s-'+info['stars']+'" data-default="'+info['stars']+'">0 stars</span>';
//add this to html
$(this).find("[data-role=content]").html(info_view);
});
$(function(){
$('body').on({
mousemove: function(e){
var $this = $(this);
// Calculate number of stars
var currentMousePosition = e.pageX - $this.offset().left;
var width = $this.width();
var rounded = Math.round((currentMousePosition/width)*10);

var starNumber = rounded/2;

// Remove + add Classes + Store current rating
$this.removeClass().addClass('stars s-' + starNumber).attr('data-rating', starNumber);
},
mouseleave:function(){
var $this = $(this);
$this.removeClass().addClass('stars s-' + $this.attr('data-default'));
},
click: function(){
var $this = $(this);
//Hide the current rating selector
$this.replaceWith($('<div>', {
'class': 'loading'
}));

// Send the request
$.post('rating.php',{
rating: $this.attr('data-rating')
}, function(d){
// Handle response
if(d.result == 'error'){
alert(d.msg);
} else {
$this.removeClass().addClass('stars s-' + d.rating).attr('data-default', d.rating)
$('.loading').replaceWith($this);
}
}, 'json');
}
}, '.stars');
});

谢谢!!

最佳答案

好的,我已经对你的 fiddle 做了一些修改,你可以找到我的版本here

请注意我已经删除了

<span class="stars s-2.5" data-default='2.5'>
0 stars
</span>

来自您的 html 的部分并将其添加到 javascript$(document).on("pagebeforeshow", "#details-page", function () {下功能

因为在您的原始代码中,所有产品只有一组星标,但通过此更改,每个产品都有一组星标。

然后我添加了"stars": info 的键数据集,以便每条记录都有自己的速率值,然后添加一个 data-id属性为 <span>对于星星并将值添加到 data-default属性。

有了它,您可以使用它的 data-id 访问每个产品的费率和 data-rating属性。

希望这可以解决您的问题,请将结果更新给我们。

关于php - JSON 单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29520707/

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