我目前正在學習基本的 php 和 jQuery。
我創建了在滑鼠懸停時獲取 url 的腳本,并將其發送到 php。
問題是,如果我想將此資料傳遞給 php 變數,它似乎不起作用,因為它只回顯“'這是我們的 JS 變數:'”
腳本:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
函式.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
uj5u.com熱心網友回復:
解決方案:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];
uj5u.com熱心網友回復:
問題是 - 當頁面加載時,變數的值為空。所以解決方案是在滑鼠懸停的那一刻呼叫ajax。
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/395585.html
標籤:php 阿贾克斯 WordPress的 回声
