当我点击一个链接时,有没有办法更新数据到mysql数据库?我想在我的网站上创建一个评论投票系统,这样当用户点击“为此评论投票”链接时,+1应发送到数据库中…
那件事怎么可能?
发布于 2010-07-11 22:53:14
HTML
<form method="post" action="/vote.php">
<input type="hidden" name="item" value="999">
<input type="submit" name="submit" value="Vote Up">
</form>PHP - vote.php
<?php
if( !isset( $_POST['item'] ) ) {
header( 'HTTP/1.0 404 Not Found' );
die( '<html><body>Missing <i>item</i> parameter</body></html>' );
}
$item = (int) $_POST['item'];
if( @mysql_query( "UPDATE `items` SET `vote`=`vote`+1 WHERE `id`=$item" ) ) {
if( isset( $_POST['format'] ) && $_POST['format']=='json' )
die( json_encode( array( 'result'=>true ) ) );
die( '<html><body>Score for item #'.$item.' incremented</body></html>' );
}
header( 'HTTP/1.1 500 Internal Server Error' );
if( isset( $_POST['format'] ) && $_POST['format']=='json' )
die( json_encode( array( 'result'=>false ) ) );
die( '<html><body>Score for item #'.$item.' FAILED to incremented</body></html>' );jQuery
$( document ).ready( function() {
$( 'form[action="/vote.php"]' ).each( function() {
$( this ).replaceWith( '<span class="vote" parameter="item='+$( this ).find( 'input[name="item"]' ).attr( 'value' )+'">Vote Up</span>' );
} );
$( 'span[class="vote"]' ).click( function() {
var $this = $( this );
$.ajax( {
type : 'POST' ,
url : '/vote.php' ,
data : $( this ).attr( 'parameter' )+'&format=json' ,
dataType : 'json' ,
success : function( data , status , XHR ) {
if( data.result===true )
alert( 'Voted Up' );
else
alert( 'Something Unexpected Borked' );
} ,
error : function( XHR , status , error ) {
alert( 'Something Borked' );
}
} );
} );
} );注意:这是一个未经测试的解决方案,但我认为这是开始调试和测试的起点。
更新:根据@Artefacto的建议将行为更改为发布。
发布于 2010-07-11 18:31:38
当然,创建一个PHP脚本来更新数据库,就像提交了一个常规表单一样,然后在单击链接时使用Javascript向该脚本发出请求。
发布于 2010-07-11 18:32:46
使用AJAX (通过可用的框架jQuery、mootools、Dojo等之一):每当用户点击一个链接时,就会触发一个附加的操作并执行“魔术”。
大多数情况下,这将向服务器发送一个带有注释id和/或任何其他所需数据的AJAX请求,脚本将更新数据库。
SInce你已经用jQuery标记了这个问题,http://api.jquery.com/category/ajax/是一个很好的起点。
https://stackoverflow.com/questions/3222697
复制相似问题