我正在尝试将ajax自动保存添加到插件中的设置页面并制作此代码:
json ='{"results":[{"eventName":"Rey","name":"Tar","dateOfShow":"2017-01-27T22:00:00","userGroupName":"Bit","eventHallName":"Grnn","imageSource":"test2.jpg"},{"eventName":"Gor","name":"Skum","dateOfShow":"2017-01-30T20:00:00","userGroupName":"Gaf","eventHallName":"Gai","imageSource":"test1.jpg"}]}';
res = JSON.parse(json)
alert(res.results.length);
var i = 0;
while(i<res.results.length)
{
alert(res.results[i].eventName)
i++;
}
我发现每次我想发送这个简单的ajax请求的问题我得到<?php
function cfgeo_settings_javascript() { ?>
<script type="text/javascript" >
(function($){
$(document).ready(function(){
$("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
var This = $(this),
name = This.attr("name"),
value = This.val(),
data = {};
data['action'] = 'cfgeo_settings';
data[name] = value;
console.log(data);
console.log(ajaxurl);
$.post(ajaxurl, data).done(function(returns){
console.log(returns);
});
});
});
}(window.jQuery));
</script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');
function cfgeo_settings_callback() {
global $wpdb; // this is how you get access to the database
var_dump($_POST);
if (isset($_POST)) {
// Do the saving
$front_page_elements = array();
$updates=array();
foreach($_POST as $key=>$val){
if($key != 'cfgeo_settings')
update_option($key, esc_attr($val));
}
echo 'true';
}
else
echo 'false';
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>
真正令人讨厌的事情。
当我尝试在选择选项框中进行一些更改时,这是控制台日志:
0
我的ajax调用或PHP脚本出了什么问题?
我需要提一下两个代码都在一个PHP文件中。
答案 0 :(得分:1)
以下是注释中包含注释的工作示例,代码中有很多内容,本示例在代码注释中解决了这些问题。 https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc
答案 1 :(得分:1)
你应该遵循这个管理员ajax参考的WordPress ajax方法的指导方针。请遵循这个。