[英]How to Change PHP Variable in WordPress using Ajax
我正在嘗試以非常基本的方式學習 ajax 如何傳遞變量,但我有但找不到非常基本的教程。 我想要實現的是更改顯示參數的變量
頁面模板.php
$args = get_posts( array(
'post_type' => $posttype,
));
<input type="checkbox" id="toys">
<input type="checkbox" id="games">
$('#toys').click(function() {
if ($(this).is(':checked')) {
$.ajax ({
type:'POST',
url: //not sure what to put here
data: //not sure what to put here
success: function(data)
{
//how to change the post type variable?
}
});
} else {
}
});
功能。php
add_action('wp_ajax_nopriv_change_posttype','change_posttype');
add_action('wp_ajax_change_posttype','change_posttype');
function change_posttype() {
$posttype ='toys'; // here is my problem of what should I put in here for ajax to process
}
我曾經使用這個簡單的模板來發布數據,使用 jquery、ajax 和 php,希望它對你有用。
注意:在您的 html 中,您必須放置 jquery 和 ajax 的 CDN 文件
//在你的 html
<form id="form">
<inpunt type="text" id="field1">
<inpunt type="text" id="field2">
<input type="radio" name="field3" value="1">
<input type="radio" name="field3" value="1">
</form>
<div id="publishAnswer">
<!-- here will be the php answer -->
</div>
//在app.js中
$('#form').submit(function(event) {
event.preventDefault();
var valFieldOne = $('#field1').val();
var valFieldTwo = $('#field2').val();
var valFieldThree = $('input:radio[name=field3]:checked').val();
$.post('yourFile.php', {
valFieldOne: valFieldOne,
valFieldTwo: valFieldTwo,
valFieldThree: valFieldThree
},function(reponse) {
console.log(reponse);
let data = JSON.parse(reponse);
let result = '';
data.forEach(data => {
result += `<p>${data.result}</p>`
});
$("#publishAnswer").html(result);
});
});
//yourFile.php
<?php
$submitedFieldOne = stripslashes($_POST['valFieldOne']);
$submitedFieldTwo = stripslashes($_POST['valFieldTwo']);
$submitedFieldThree = stripslashes($_POST['valFieldThree']);
$json[] = array (
'result'=>"Ok Recieved",
'notes'=>"Worked",
);
$jsonstring = json_encode($json);
echo $jsonstring;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.