2 回答
TA贡献1835条经验 获得超7个赞
首先,如果你想直接与 PHP 和 JavaScript 交互,你应该确保你的脚本在那个 .php 文件上,这意味着里面的脚本标签没有被导入。
现在既然要在 php 中显示一个变量,我们使用echo,你应该用这个替换你的代码。
$( function() {
var postID = '<?php echo $id; ?>';
var rating = new starRating( { // create first star rating system on page load
containerId: '<?php echo $id; ?>', // element id in the dom for this star rating system to use
starWidth: 60, // width of stars
starHeight: 60, // height of stars
ratingPercent: '0%', // percentage star system should start
canRate: true, // can the user rate this star system?
user: '<?php echo $userLoggedIn; ?>',
onRate: function() { // this function runs when a star is clicked on
//console.log( rating );
$.ajax({
url: '../handlers/starating.php',
type: 'POST',
data: 'post_id='+postID+'&rating_num='ratingPercent,
dataType: 'json',
success: function(){
console.log('works');
}
});
//alert('You rated ' + rating.newRating + ' starts' );
}
} );
} );
TA贡献1936条经验 获得超7个赞
首先,将php代码直接包含在js文件中并不是一个好主意,其中有很多原因,可读性、安全性等。这两者应该严格分开,并且ajax可以控制之间发生的事情。
这是一个例子:
JS
function Call_AJAX({do_action,ajax_id,do_success}) {
$.ajax({
type : 'POST',
url : ajax_url,
dataType : 'json',
data : {
action : do_action,
id: ajax_id
},
success : do_success
});
};
php
function call_php_function(){
$id = $_POST['id'];
//Do something wit the call then return result
$result = do_something();
echo json_encode($result);
exit;
};
然后你可以这样称呼它js:
//Get some sort of result
var result_append = function (data) {
//Do something with the returned data
console.log(data.result)
};
Call_AJAX(
do_action = 'call_php_function',
ajax_id = some_ajax_id,
do_success = result_append);
这样,您可以调用php(如call_php_function())中的特定函数,然后获取评分信息。得到结果后,通过json_encode. 一旦 ajax 调用成功,您就可以显示它们。您可以在双方实施错误处理。这样前端发生的任何事情都不会影响后端,反之亦然。
希望这可以帮助。
- 2 回答
- 0 关注
- 148 浏览
添加回答
举报
