有人可以给我一个很好的例子来说明如何使用 Ajax 调用 PHP 函数吗?我正在尝试将图片库(具有动态数量的图像)保存到管理设置部分的数据库中。下面的代码不完整或者可能有一些错误。请给我一个很好的例子或更好的方法:
<button type="button" class="btn btn-primary" onclick="jsAddSettingsFields()">Save Changes</button>
function jsAddSettingsFields(){
var elements = document.getElementsByTagName("img");
var urlsdata = new Array();
for (var i = 0, element; element = elements[i++];) {
if (elements[i].id == "idGalPic") {
urlsdata[i] = elements[i].src;
// now we have all image urls in array, now need to
// call add_settings_fields
var data = {
action: 'php_addsettingsfields',
p_urls: urlsdata //I think i need to JSON this
};
jQuery.post( "", function( data ) );
}
}
}//end of js function
<?php
add_action( 'wp_ajax_update_options', 'php_addsettingsfields_callback' );
add_action( 'wp_ajax_nopriv_update_options', 'php_addsettingsfields_callback' );
function php_addsettingsfields_callback() {
$pic_urls = $_POST['p_urls']; // De-JSON-fy this variable
foreach ($pic_urls as &$url) {
add_settings_field($url);
}
add_settings_field(
'pic_url_id', // ID - slug name of field
'', // Title
array( $this, 'pic_gal_callback' ), // Callback
'TestPlugin', // Page
'setting_section_id' // Section ID - slug name of page
);
public function pic_gal_callback() {
<input type="hidden" id="idPic" name="idPic" value=$url />
}
// after all hidden fields(with gallery pic urls) are added to setting section submit
// the page and save the gallery urls to database
MMMHUHU