我对 WordPress 还很陌生,遇到了一些我自己无法解决的问题。
我的目标是使用用户在文本框中输入的输入来更新 session 变量。
然后我想将更新的 session 变量存储到文本文件中。
我正在使用 jquery 和 ajax。我的代码不起作用。任何帮助都会很棒。谢谢。
我会尽力解释我的代码。 如果我不清楚,我很乐意添加其他信息。
该表单包含以下代码:
<input type="text" id="question_in" />
<input type="button" id="btn" value="Add" />
我的 wordpress header.php 包含以下内容:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
jQuery('#btn').click(function() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
updateSession();
});
function updateSession(){
alert ("in updateSession!"); //for testing this displays
var new_question = $("#question_in").val(); alert ("input is "+new_question); // for testing this works
// This does the ajax request
$.ajax({
type:"POST",
url: "write-test.php",
data: "question=" + new_question,
success:function(){
alert ("in success!"); //this displays
},
error: function(errorThrown){
alert ("There is an error!");
}
});
}
</script>
这是 write-test.php 的代码
<?php
session_start();
if(isset($_POST['question'])) {
$theQuestion = $_POST['question'];
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $theQuestion);
fclose($myfile);
?>
最佳答案
The correct way to handle this is to use WP's admin-ajax.php file, instead of your own. See this Codex page:
http://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Viewer-Facing_Side
Instead of putting the code in a custom php page, just put it in your functions.php file.
关于php - WordPress;使用 jquery 和 ajax 更新和存储 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709700/