Схема того, что вы могли бы сделать.Я сделал некоторые предположения и выбрал GET, используя метод URL вместо POST;отредактируйте по вкусу, если вы предпочитаете использовать POST.
Еще одно примечание - вы можете захотеть иметь таблицу флагов, чтобы вы могли следить за тем, кто пометил, кому, возможно, позволить им добавить комментарий и т. д... Просто мысль.
Это просто для того, чтобы дать вам представление о том, как вы можете делать то, что просите.Я не проверял код, поэтому покупатель остерегается.Это только отправная точка.
view.php
Здесь у вас есть ссылка, по которой конечный пользователь щелкнет, чтобы активировать сценарий флага.Где-то в вашей разметке у вас будет что-то вроде ...
<a class="flag" href="flag.php?comment=100">Flag</a>
Тогда в содержимом view.php у вас будет код события click, который выполняет асинхронный javascript-запрос jQuery ($ .ajax ()в этом случае это может быть $ .get или $ .post или вообще другая библиотека, например MooTools или Prototype).
В примере показано, что сервер будет возвращать текст в формате JSON в аргументе данных, который затемоценивается, чтобы проверить, что сервер ответил (успех? сбой? частичный успех? требуется вход в систему?).См. http://json.org/.
<script type="text/javascript">
$(document).ready(function(){
$('a.flag').click(function(event){
$.ajax({
type: "GET",
url: $(this).attr('href'),
data: dataString,
dataType: "json",
success: function (data) {
if (data.error == -1) {
// Not logged in, redirect to login page.
window.location = 'login.php';
} else if (data.flagged == 1 && data.count != -1) {
// Success! With a count too.
alert('Comment flagged ('+data.count+' times flagged).');
} else {
switch(data.error) {
case 1:
alert('Comment not found');
break;
case 2:
alert('Comment not flagged due to an update error.');
break;
case 3:
alert('Comment flagged but count not returned.');
break;
default:
alert('There was a general error flagging the comment.');
break;
}
}
},
error: function(){
alert('Comment not flagged; general send error.');
}
});
// Call these to prevent the a tag from redirecting
// the browser to the a-tags href url.
event.preventDefault();
return false;
});
});
</script>
flag.php
flag.php - это страница сервера, которая позволяет вам выполнить запрос mysql, используя, конечно, PHP, изатем ответьте текстом в формате JSON.Содержимое (текст), возвращаемый страницей, будет выглядеть примерно так:
{"flagged":1,"count":15,"error":0}
Это будет указывать вашей вызывающей странице (в браузере), что комментарий был помечен, был помечен 15 раз (плохо, плохокомментарий), и что ошибок не было.
ЭТО ВАЖНО : не эквивалент HTML.Этот тип текста является данными и анализируется обратно в объект Javascript в ответ на функцию $ .ajax ().Поэтому не размещайте HTML-код вокруг него, поскольку это не то, что вы должны делать.См. http://www.json.org/example.html для примеров.
<?php
// Need to output JSON headers and try to prevent caching.
session_cache_limiter('nocache');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
// Our JSON array to return
// - flagged would be 1 = success, 0 = failure
// - count would return the # flags, with -1 no return #
// - error code, see comments for description
$json = array('flagged'=>0,'count'=>-1,'error'=>0);
// Your logged in check code goes here
// you don't want non-logged in people doing this
// Here, however you test to find out if someone is logged in,
// check and return a -1 error to redirect the login.
if (!$logged_in) {
// error -1 = not logged in, redirect browser
$json['error'] = -1;
exit(echo(json_encode($json)));
}
// Your mysql connection code goes here
$comment = mysql_real_escape_string($_GET['comment']);
if (empty($comment) || !is_numeric($comment)) {
// error 1 = comment id not found
$json['error'] = 1;
} else {
$result = mysql_query("
UPDATE comments
SET flags = flags+1
WHERE commentID = $comment
");
if (!$result) {
$json['flagged'] = 0;
// error 2 = update error
$json['error'] = 2;
} else {
$json['flagged'] = 1;
$count = mysql_query("
SELECT flags
FROM comments
WHERE commentID = $comment
LIMIT 0, 1
");
if ($count) {
$query = mysql_fetch_assoc($count);
$json['count'] = $query['count'];
} else {
// error 3 = updated but did not get count
$json['error'] = 3;
}
}
}
echo json_encode($json);
?>