我正在创建一个用评级系统评估不同产品的项目,但由于我是新手,我有几个问题。
首先,为了实现这个目标,我创建了一个listview,它允许我使用从这个数据库中获得的JSON代码在MySQL数据库的记录中显示信息。
现在项目就像这样http://jsfiddle.net/c52m6smg/1/。 我的问题如下,我可以通过AJAX调用替换var info来从外部文件或存储在localhost上的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 field:
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');
});
谢谢!
答案 0 :(得分:0)
好的,我已经对你的小提琴进行了一些修改,你可以找到我的版本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
属性访问每种产品的费率。
希望这可以解决您的问题,请告知我们结果。