javascript - 使用ajax从javascript调用php函数的问题
问题描述
我正在尝试建立一个评级系统,需要从文件 startating.php 调用一个函数并在那里传递变量 - $id(post id)和评级百分比。我不知道如何调用这些变量,然后在 startating.php 中引用它们这是我的代码:
$( function() {
var postID = <?php echo $id; ?>;
var rating = new starRating( { // create first star rating system on page load
containerId: '$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: '$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' );
}
} );
} );
解决方案
Welcome to the community.
First of all, it is not a good idea to include php
code directly in the js
file, for many reasons among them, readability, security etc. These two should be strictly separated and have the ajax
to control what happens between.
Here is an example:
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;
};
then you can call this like this in 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);
This way, you can call a specific function in php
(such as call_php_function()
), then get the rating information. Once you got the result, then send it back via json_encode
. And you can display them once ajax call is a success. You can implement error handling in both sides. This way that whatever happens in front-end doesn't affect the back-end, visa versa.
Hope this helps.
推荐阅读
- javascript - 如果在滚动页面时调整窗口大小,如何使此效果起作用
- android - 如何为典型的手机屏幕 480x800 hdpi 创建布局?
- javascript - 外部css在reactjs中自动转换为内部css,因此无法应用多个css文件
- android - PyQt5 GUI for android vs Kivy GUI
- html - 使用 CSS 类继承引导网格系统
- javascript - Javascript:检查网址是否有效并以“http//”或“https://”开头
- c# - 过滤某些单词的 HTML 文件的最佳方法
- r - “dplyr”不知道分开
- angular - 如何在 Angular 中添加烤面包机?
- jquery - 如何使用 jquery 在 Angular 7 中使用引导弹出框?